How to Create Migration in the Laravel Framework?

Migration allows to create, update, and delete tables through the PHP class-based code and command. Migration class has two methods which are up and down. In the up method, anything you can do like create the table, modify the columns, etc. In the second method, Laravel reverts the changes from the up() method.

Create Migration in Laravel

Let’s create a migration for the order table by following the command,

php artisan make:migration create_orders_table

The above command creates a migration file in the migrations folder inside the database directory located on the root.

Create Migration

Next, open the migration file and add a few columns through Laravel’s built-in functions. By default, the migration has id() and timestamps() that creates created_at and updated_at columns.

create order table
public function up()
{
    Schema::create('orders', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description')->nullable();
        $table->boolean('status')->default(0);
        $table->timestamps();
    });
}

This script would create an order table with six columns. The last timestamps() function creates two columns. Next, we need to create an order table through the above code. Let’s run the below command,

php artisan migrate
Migrate Tables

This command runs up() function from migration files and then inserts file names along with batch numbers into the migrations table. When we run php artisan migrate command, it creates one batch number and inserts it along with file names that belong to the operation.

Order Table

Rollback Command in Laravel

Rollback command runs down() method from migration files. We always revert the changes in the down() method. For example, if we create an order table in the up() method then it should remove from the down() method.

public function down()
{
    Schema::dropIfExists('orders');
}

The above method removes the order table. Following is the command that will call down() method,

php artisan migrate:rollback
Migrate rollback

Conclusion

In this article, we covered the following,

  • Laravel migration introduction
  • Create and migrate migration
  • Rollback migration