Sometimes after migration, we may need to change our database table schema in laravel migration. That time, we do not want to lose previous data. So, in this tutorial, I will show you how to add new column in table using migration in laravel 9 as well as how to add new column in laravel migration without losing data. 

So if you do not know add column migration laravel 9, then this example is for you. We can do it using a simple migration command. Assume we have to add a new column to posts table. Just run the below command to do it:

php artisan make:migration add_slug_column_to_posts_table

 

Now if your run this command, you will get a migration file like:

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            //define your new column here
        });
    }

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

 

Now if you run php artisan migrate, your new field will be added in your posts table without losing data.

 

Read also: How To Define Foreign Key Constraint In Laravel Migration?

 

Conclusion

I have tried to discuss the clear concept of how to add new column in laravel migration without losing data. Now we know laravel add column to existing table. Hope this add column migration laravel 9 tutorial will help you.