How to add column in laravel existing table through migration

How to add column in laravel existing table through migration

While working on the laravel application, we create migration file to create tables in the database. And after migrating these migrations if we need to add columns in the table through migration then we will also need to create migration to new column  in laravel existing table.

So let’s see how can we create migration file for adding new column. Basically we will need to run a command in the terminal to create a migration. Here i am assuming we already have users table and need to add profile column.

php artisan make:migration add_profile_to_users

Now open newly created migration file and add profile column in the table schema and now this migration file will look a like below.

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']);
        });
    }
}

After doing this, now we will need to run this migration to create actual column in the table. So open your terminal and run the following command.

php artisan migrate

After running the above command, you can see the profile column in users table. And now you can say you are able to add column in laravel existing table.

You can also read the how to load gravatar in laravel by clicking on the link below.

How to load gravatar image in laravel using laravel-gravatar package