Creating and Managing Databases with Migrations in Laravel

In Laravel, migrations provide a convenient way to create and manage database schemas. Migrations are like version control for your database, allowing you to modify the database structure over time and keep track of changes. Here's a step-by-step guide on using migrations in Laravel:

 

Creating a Migration

To create a new migration, you can use the make:migration Artisan command. For example, to create a migration for creating a users table, run the following command:

php artisan make:migration create_users_table

 

Defining the Schema

Open the generated migration file in the database/migrations directory. In the up method, you can define the schema for your table using the Laravel schema builder. For example, to create a users table with name and email columns, you can use the create method:

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

 

Running Migrations

To execute the migrations and create the corresponding tables in the database, use the migrate Artisan command:

php artisan migrate

 

Rollback

If you need to undo a migration, you can use the migrate:rollback command. This will revert the last batch of migrations:

php artisan migrate:rollback

 

Managing Migration Status

Laravel keeps track of which migrations have been executed using a migrations table in the database. You can use the migrate:status command to see the status of each migration:

php artisan migrate:status

 

Modifying Tables

If you need to modify an existing table, you can create a new migration using the make:migration command and use the schema builder's methods like addColumn, renameColumn, or dropColumn to make the necessary changes.

 

Using migrations in Laravel provides a structured and efficient way to create and manage database schemas. By using version control-like functionality, you can easily make changes to your database structure and keep track of those changes over time.