How to make Laravel migration

Learn how to migrate your Laravel data with a step-by-step example.

Creating a Migration in Laravel

Creating a migration in Laravel is a straightforward process. By using the artisan command line interface, you can quickly generate and run migrations that will create, modify, or delete database tables and columns.

To create a migration, you can use the make:migration artisan command. This command will generate a migration file in the database/migrations directory. The filename will be prefixed with a timestamp, so that Laravel can determine the order of the migrations:

php artisan make:migration create_users_table

Migration created successfully!

The generated migration will contain a up() and down() method. The up() method is used to add new tables, columns, or indexes to your database, while the down() method should reverse the operations performed by the up() method. For example, to create a users table, you could use the following code in the up() method:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Once you have written your migrations, you can execute them using the migrate artisan command:

php artisan migrate

Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table

Laravel will automatically create the migrations table in your database to keep track of which migrations have already been run. This allows you to easily rollback and re-run migrations, as needed.

By using migrations, you can easily version-control your database and make sure that all developers on the project are working with the same schema. Migrations are an essential part of every Laravel project, and are a great way to keep your database in sync with your application code.

Answers (0)