How to create Laravel migration

Learn how to create Laravel migrations with an example. Get ready for a powerful database structure!

Migrations are an essential part of the Laravel framework. They are used to create and modify the database structure of a Laravel application. In this article, we will go over how to create a migration and use it to modify our database.

Step 1: Create a Migration

To create a migration, use the command php artisan make:migration. This command will create a new file in your database/migrations directory. The file will have a name similar to YYYY_MM_DD_hhmmss_create_table_name.php, where YYYY is the year, MM is the month, DD is the day, hh is the hour, mm is the minute, and ss is the second.

Inside the migration file, you will see the up() and down() methods. The up() method is used to make changes to the database, such as creating a new table or modifying an existing one. The down() method is used to undo the changes made in the up() method.

For example, if we wanted to create a new table called users, we would use the Schema::create() method in the up() method to create the table, and the Schema::drop() method in the down() method to drop the table:

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

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

Step 2: Run the Migration

Once you have created your migration, you can run it using the command php artisan migrate. This command will run all of the migrations that have not yet been executed. You can also specify the name of a specific migration to run only that migration.

For example, if you wanted to run the users migration that we created in Step 1, you would use the command php artisan migrate --path=database/migrations/YYYY_MM_DD_hhmmss_create_users_table.php, where YYYY is the year, MM is the month, DD is the day, hh is the hour, mm is the minute, and ss is the second.

Once the migration has been executed, you can check the database to make sure that the table was created correctly. You can also run the down() method to undo the changes made by the migration.

Conclusion

In this article, we went over how to create and run a migration in Laravel. We also discussed how to use the up() and down() methods to make changes to the database. Migrations are an essential part of any Laravel application and are a great way to keep your database structure up-to-date.

Answers (0)