How to create migration in Laravel

Learn how to create Laravel migrations with an example for better database management.

Migrations are an important part of the Laravel development process, allowing developers to easily create, modify, and delete database tables and columns. In this tutorial, we'll show you how to create migrations in Laravel.

Step 1: Create a Migration File

The first step is to create a migration file. A migration file is a special type of file that contains instructions for setting up the database. To create a migration file, open a terminal window and run the following command:

php artisan make:migration create_users_table 

This command will create a new migration file in the database/migrations directory. The file will have a unique name that includes the timestamp of when it was created. The file will also include a class, which contains the instructions for setting up the database.

Step 2: Add Columns to the Table

Once the migration file is created, we need to add the columns to the table. To do this, we'll use the Schema facade. The Schema facade provides a number of methods that can be used to add columns to the table. For example, if we want to add a name column to the users table, we can use the string method like this:

Schema::table('users', function (Blueprint $table) {
    $table->string('name');
});

This will add a name column to the users table. We can add as many columns as we need. Once we're finished adding the columns, we can move on to the next step.

Step 3: Run the Migration

Once the migration file is created and the columns are added, we need to run the migration. To do this, open a terminal window and run the following command:

php artisan migrate

This will run all of the pending migrations. Once the migrations are finished, the database will be set up according to the instructions in the migration file.

And that's it! We've now created a migration in Laravel and set up the database according to our instructions. Migrations are an important part of the Laravel development process, and they make it easy to make changes to the database quickly and easily.

Answers (0)