What is the use of migration file in Laravel

Laravel migration is a way that makes you to create a table in your database. It enables this without going to the database manager, i.e. SQLite or phpmyadmin for database creation. A migration file in Laravel sets up the database structure and tables as in database managers.

These migrations act like a version control for your database. It allows your team to change and share your application’s database schema. Moreover the migrations are paired with Laravel’s schema builder and they create your application’s database schema.

The Laravel Schema facade allows unbelievable database support to create and manipulate tables across entire Laravel’s supported database systems.

Generate a migration file

The artisan make:migration command with the corresponding table name creates a new database migration.

php artisan make:migration create_new_table

This new migration comes under the database/migrations directory. A migration file has a timestamp, which enables Laravel to keep track of the order of the migrations.

Contents of migration file in Laravel

public function up()
    Schema::create('users', function (Blueprint $table) 

As seen above, the migration file has Schema::create function and columns names of the table within the function. This creates a users table with table columns as ‘name’, ‘contact’, and ‘status’. It does the same functions as performed in database managers like PhpMyAdmin.

Create new table structure

Once a migration file is made, to run any new migration, the php artisan command is passed.

php artisan migrate

This helps create a new table structure, whenever a new migration file is created and populated with table details.

Reverse a migration

Each new migration can be rolled back or revered using the commands below.

php artisan migrate:rollback

The command above rolls back multiple ‘recent’ migrations. To specify the number of ‘last’ migrations to be reversed. You can specify the number.

php artisan migrate:rollback --step=8

This rolls back the last 8 migrations.

To reset entire migrations made for the Laravel application. Use the command below.

php artisan migrate:reset

Benefits of migration file in Laravel

The main benefit of migrations is that it acts as a development server. It allows you to change the schema any time during development. Moreover it also allows to migrate, rollback migrations, and re-migrate them, and as soon as your application is done. Laravel migrations handles the production environment automatically for you.

PhpMyAdmin, requires us to create tables and edit fields manually and locally and in a remote server, and has a risk of forgetting something and that can break your application. Moreover, if there is more than one server for your application, its a bigger problem.