Posts Learn Components Snippets Categories Tags Tools About
/

How to Add a New Column to an Existing Table Migration in Laravel

Learn how to add a new column in an existing table migration in Laravel to alter the table that you have migrated.

2 years ago

5 mins read

1758 views

In this short post, you'll learn to add a new column to an existing migration. The steps are very simple so let's get started. For this scenario imagine you have a "Post" model with a corresponding "create_posts_table" file and you want to add new "slug" and "summary" columns to the existing table.

Before (Post Model)

  • id
  • title
  • content
  • image
  • created_at

After (Post Model)

  • id
  • title
  • slug (new column to be added)
  • summary (new column to be added)
  • content
  • image
  • created_at
Now that we can see clearly how the table structure will look like, let's define the migration to add the new columns.

Create the Migration


To add a new column you have to run the make migration command but instruct it as adding instead of creating a new migration. Make use of the "--table=your-table-name" flag and specify the table that you want to add new columns.
# for multiple columns like the scenario
php artisan make:migration add_additional_columns_to_posts_table --table=posts

# for single column you can explicitly mention it
php artisan make:migration add_slug_to_posts_table --table=posts
Upon success, the command will output as follows.
Created Migration: 2021_06_14_210156_add_additional_columns_to_posts_table

Define the Columns


The command will create a new migration class called AddAdditionalColumnsToPostsTable and here define the columns to add to the migration in the "up" method. For the "down" method, drop the column as necessary and this will be called when the migration rollback command is executed.
<?php

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

class AddAdditionalColumnsToPostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('slug')->unique();
            $table->text('summary')->nullable();
        });
    }

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

Run the Migration


Finally, run the migration command and the 2 new columns will now be available in the table.
php artisan migrate
By now you will be able to add a new migration in few simple steps. If you find this tutorial to be helpful do share it with others and cheers 🍻. happy coding!

Alternative Tags

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)