[php] Add a new column to existing table in a migration

I can't figure out how to add a new column to my existing database table using the Laravel framework.

I tried to edit the migration file using...

<?php

public function up()
{
    Schema::create('users', function ($table) {
        $table->integer("paid");
    });
}

In terminal, I execute php artisan migrate:install and migrate.

How do I add new columns?

This question is related to php laravel laravel-4 laravel-migrations

The answer is


this things is worked on laravel 5.1.

first, on your terminal execute this code

php artisan make:migration add_paid_to_users --table=users

after that go to your project directory and expand directory database - migration and edit file add_paid_to_users.php, add this code

public function up()
{
    Schema::table('users', function (Blueprint $table) {
         $table->string('paid'); //just add this line
    });
}

after that go back to your terminal and execute this command

php artisan migrate

hope this help.


I'll add on to mike3875's answer for future readers using Laravel 5.1 and onward.

To make things quicker, you can use the flag "--table" like this:

php artisan make:migration add_paid_to_users --table="users"

This will add the up and down method content automatically:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        //
    });
}

Similarily, you can use the --create["table_name"] option when creating new migrations which will add more boilerplate to your migrations. Small point, but helpful when doing loads of them!


If you're using Laravel 5, the command would be;

php artisan make:migration add_paid_to_users

All of the commands for making things (controllers, models, migrations etc) have been moved under the make: command.

php artisan migrate is still the same though.


Add column to your migration file and run this command.

php artisan migrate:refresh --path=/database/migrations/your_file_name.php

Although a migration file is best practice as others have mentioned, in a pinch you can also add a column with tinker.

$ php artisan tinker

Here's an example one-liner for the terminal:

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ $table->integer('paid'); })



(Here it is formatted for readability)

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ 
    $table->integer('paid'); 
});

laravel 5.6 and above

in case you want to add new column as a FOREIGN KEY to an existing table.

Create a new migration by executing this command : make:migration

Example :

php artisan make:migration add_store_id_to_users_table --table=users

In database/migrations folder you have new migration file, something like :

2018_08_08_093431_add_store_id_to_users_table.php (see the comments)

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddStoreIdToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Create new column
            // You probably want to make the new column nullable
            $table->integer('store_id')->unsigned()->nullable()->after('password');

            // 2. Create foreign key constraints
            $table->foreign('store_id')->references('id')->on('stores')->onDelete('SET NULL');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Drop foreign key constraints
            $table->dropForeign(['store_id']);

            // 2. Drop the column
            $table->dropColumn('store_id');
        });
    }
}

After that run the command :

php artisan migrate

In case you want to undo the last migration for any reason, run this command :

php artisan migrate:rollback

You can find more information about migrations in the docs


You can add new columns within the initial Schema::create method like this:

Schema::create('users', function($table) {
    $table->integer("paied");
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

If you have already created a table you can add additional columns to that table by creating a new migration and using the Schema::table method:

Schema::table('users', function($table) {
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

The documentation is fairly thorough about this, and hasn't changed too much from version 3 to version 4.


Laravel 7

  1. Create a migration file using cli command:

    php artisan make:migration add_paid_to_users_table --table=users

  2. A file will be created in the migrations folder, open it in an editor.

  3. Add to the function up():

Schema::table('users', function (Blueprint $table) {
    // Create new column
    // You probably want to make the new column nullable
    $table->integer('paid')->nullable()->after('status');
}
  1. Add to the function down(), this will run in case migration fails for some reasons:

    $table->dropColumn('paid');

  2. Run migration using cli command:

    php artisan migrate


In case you want to add a column to the table to create a foreign key constraint:

In step 3 of the above process, you'll use the following code:

$table->bigInteger('address_id')->unsigned()->nullable()->after('tel_number');

$table->foreign('address_id')->references('id')->on('addresses')->onDelete('SET NULL');

In step 4 of the above process, you'll use the following code:

// 1. Drop foreign key constraints
$table->dropForeign(['address_id']);
// 2. Drop the column
$table->dropColumn('address_id');

WARNING this is a destructive action. If you use this ensure you back up your database first

you can simply modify your existing migration file, for example adding a column in your table, and then in your terminal typing :

$ php artisan migrate:refresh

First rollback your previous migration

php artisan migrate:rollback

After that, you can modify your existing migration file (add new , rename or delete columns) then Re-Run your migration file

php artisan migrate

First you have to create a migration, you can use the migrate:make command on the laravel artisan CLI.Old laravel version like laravel 4 you may use this command for Laravel 4:

php artisan migrate:make add_paid_to_users

And for laravel 5 version

for Laravel 5+:

php artisan make:migration add_paid_to_users_table --table=users

Then you need to use the Schema::table() . And you have to add the column:

public function up()

{

    Schema::table('users', function($table) {

        $table->integer('paid');

    });

}

further you can check this


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-4

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel Can I do Model->where('id', ARRAY) multiple where conditions? how to fix stream_socket_enable_crypto(): SSL operation failed with code 1 Rollback one specific migration in Laravel How can I resolve "Your requirements could not be resolved to an installable set of packages" error? Define the selected option with the old input in Laravel / Blade Redirect to external URL with return in laravel laravel the requested url was not found on this server

Examples related to laravel-migrations

Artisan, creating tables in database Laravel Unknown Column 'updated_at' Laravel Migration Change to Make a Column Nullable Add a new column to existing table in a migration