How to add new column to existing table without losing data in Laravel

  In Laravel we will learn how to add new column to existing table without losing data by using migration.
  Lets us see an example , we are going to create a migration for blogs.

  1. If you don’t know how to create migration then you can see below command otherwise leave it, and move to second point.

  Syntax

 php artisan make:migration create_tablename_table

 Example
 We will follow the syntax and create migration for blog, after created migration you can see the table. In this table there are two functionup()  for run the migration table and down() for reverse migration. Now run the below command.

    Php artisan make:migration create_blogs_table

After migration you can add table field name, we are adding one field that is “title”.

/** Run the migrations */
public function up(): void
{
   Schema::create('blogs', function (Blueprint $table) { 
        $table->id();
        $table->string('title'); 
        $table->timestamps();
   });
}

/** Reverse the migrations. */
public function down(): void
{
     Schema::dropIfExists('blogs');
}

Now run command php artisan migrate and see your table in MySQL database.

  1. Now we want to add new column “slug” in blogs existing table without losing data.

So we have to create another migration for add new column , you can put any name as per your choice so we are creating migrate with alter_blog_table” name.

php artisan make:migration create_alter_blogs_table

now you can see your migrated schema blow code in this, we have to add new field “slug” in both up() and down() function and run  artisan

   public function up(): void 
    {
      /** here you have add schema with previous table name, in previous table blogs is the table name. */
           Schema::table('blogs', function (Blueprint $table) {
                   $table->string('slug'); // add new column HERE
      });
        }

    /** Reverse the migrations. */
    public function down(): void
     {
          Schema::table('blogs', function (Blueprint $table) {
               $table->dropColumn('slug');  // Here you have to add field
          });
     }

Now you can see again blogs table in your database, new field added successfully without losing data in Laravel.