Create Migrations in Laravel

A Laravel Migration script defines database schema modifications. Create new tables, amend existing tables, add or modify columns, and seed the database with data.

Migration files are in the database/migrations directory. 

Creating tables for Laravel migrations

php artisan make:migration create_products_table
 This will generate a new migration file in your project’s database/migrations directory. The generated file’s name includes a timestamp to ensure that migrations are executed in the correct order. Inside the Laravel migration file, you can write the code to create or modify the schema of a table inside your database.

return new class extends Migration{    

    public function up(): void    {

        Schema::create('products\', function (Blueprint $table) {

            $table->id();

            $table->string('name_logistic_co', 100)->nullable();

            $table->string('address_logistic_co', 120)->nullable();            

            $table->timestamps();

        });

    }

    public function down(): void    {

        Schema::dropIfExists('logistic_companies');

    }

};


Adding Columns in Table

php artisan make:migration add_new_column_to_example_table --table=product

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

public function down()  {
       Schema::table('products', function (Blueprint $table) {
           $table->dropColumn('sku');
       });
}


Laravel migrations let you conduct database actions without using phpMyAdmin.


Removing columns from an existing table.

php artisan make:migration drop_gender_from_tests_table --table=product

public function up()
{
     Schema::table('product', function (Blueprint $table) {
     $table->dropColumn('sku');
});
}

Remove a column if it exists.

public function up()
{
        Schema::table('product', function (Blueprint $table) {   
        if (Schema::hasColumn('product', 'sku')){   
              Schema::table('product', function (Blueprint $table)   {
                         $table->dropColumn('sku);
             });
       }
    }
}

 

Drop a table

php artisan make:migration drop_products_table

public function up() 
{
   Schema::dropIfExists(table('product'));
   $table->increments('id');
   ...
}

check the final database output after migrations. Migration files are in the database/migrations directory. 

Author
Full Stack Developer

Deepak Talwar

Technical Architect & Full Stack Developer with 18+ years of Professional Experience in Microsoft Technologies & PHP Platform. Hands on experience with C#, VB, ASP.NET, ASP.NET MVC, ASP.NET Core, ASP.NET Web API, Linq, ADO.NET, Entity Framework, Entity Framework Core, Sql Server, MYSQL, NoSql, Javascript, Angular, jQuery, AWS, Azure, React, Angular, Laravel, Codeingiter, Serenity, VBA, Cloud Computing, Microservices, Design Patterns, Software Architecture, Web Design and Development.

Related Post