How to Create Migration in the Laravel Framework?

Last updated on December 29, 2022

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

Laravel has a command (php artisan make:migration file_name) that creates file in the database/migrations directory. Once you created the migration file you need to add columns in the up() function that needed to be added to the table. After these steps, you need to command that creates a table accordingly.

Also, this article demonstrates how to create a migration, add columns, run migration, and roll back migration.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: Laravel,