How to add new columns to the existing table in Laravel migration

10 Apr 2019 . Laravel . 3.8K views

Sometimes it is required to add new columns in Laravel tables. Today I will show you how to add new column or columns to the existing table in Laravel migration.

Imagine that, you have a table called users where the table structure is like this.

User table

After migration and having data into the table, now maybe you want to add a new column to the users table called profile. To add a new column, refresh database is not an ideal way. In this situation, you can create a new migration file to add a new column into the users table.

Add a single Column:

To add a new column to the existing table in Laravel, you need to add the following command in terminal.

php artisan make:migration add_profile_to_users

It will create a add_profile_to_users file in migration folder. That should be like this-

class AddProfileToUsers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('profile')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('shop_users', function (Blueprint $table) {
            $table->dropColumn(['profile']);
        });
    }
}

Now you just run the following migration command to add a new column in your table.

php artisan migrate

Now you should able to see a new column in your table, that should be like this. add a new column in the table

Add multiple columns

If you need to add multiple columns, you need to add the following command in the terminal.

php artisan make:migration add_profile_and_bio_to_users

It will generate a add_profile_and_bio_to_users file in migration folder. That contains the following link-

class AddProfileToUsers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('profile')->nullable();
            $table->string('bio')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('shop_users', function (Blueprint $table) {
            $table->dropColumn(['profile',  'bio']);
        });
    }
}

Finally, you need to run the following command to migrate that.

php artisan migrate

Hope it will work for you.