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

In laravel on 2~5 minutes
How to Add a New Column to an Existing Table in Laravel

The process of creating a new Laravel database table migration is pretty straightforward. All you need to do is create the migration and add the necessary columns to it. For example, let’s say you need to create a table called posts, then you can run the following command.

php artisan make:model -m Post

It will create the migration file along with the model. After that, you can add the necessary columns.

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('body');
        $table->timestamps();
    });
}

Now everything is fine until you need to make some changes to the existing table. Let’s assume that we need to add a new column called “slug” to the posts table. Of course, you can directly change the existing migration file, but you will not be able to apply changes to the table by running the php artisan migrate command. It will skip changes in the migration saying, “Nothing to migrate”. Now you will have to forcefully run the migration with either migrate:refresh or migrate:fresh command. But both of these commands will drop existing tables and destroy all the data in tables before re-creating tables. So to avoid that, we need to mention the necessary changes in a separate migration. For that, run the following command.

php artisan make:migration add_status_to_posts_table --table=posts

Open the newly created migration file and add the “slug” column.

public function up()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->string('slug');
    });
}

If you need to change the order of the new column, you can use ->after('column_name') as well. For example, if you need the “slug” column after the “title” column, you can use something like below.

public function up()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->string('slug')->after('title');
    });
}

Before the migration, run php artisan migrate:status to check whether there is an issue. If everything looks good and the new migration is ready, then run the migration with the following command.

php artisan migrate

Only For SQLite Databases: If you have been using SQLite as the database, then you might get an error called “SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL”. This happens because you must define a default value for the column if it is set as a NOT NULL column as quoted below in the SQLite documentation.

If a NOT NULL constraint is specified, then the column must have a default value other than NULL.

But we can easily fix it by using a default value.

public function up()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->string('slug')->default('');
    });
}