Add new column to existing table migration in Laravel

When you’re working with database in your Laravel project, and you have a table that is already migrated. Now, if you are looking to add a new column to the database table you cannot just simple edit the old migration file to add the column.

Here is how you would go about this.

1. Create a new migration file.

Let’s say you are looking to add a new field named meta to your posts table. You need to run the following artisan command to generate a new migration file.

php artisan make:migration add_meta_column_to_posts_table --table=posts

You then need to use the Schema::table() method (as you’re accessing an existing table, not creating a new one). And you can add a column like this:

Livewire Component Library

/**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('meta')->nullable();
        });
    }

If you adding a new column to the table which already have existing data then make sure to provide a default value of the column or to add nullable clause while creating the migration.

Host Laravel Application on DigitalOcean

Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.

2. Modify the down method.

Don’t forget to add the rollblack option in the down method. This would run in case you want to reverse the recent migration.


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

3. Run the migrations.

Now, you can run the migrations.

php artisan migrate

Site Footer