Laravel Migrations
Migrations in Laravel are a feature that allows you to define and manage your database schema using PHP code. They provide a structured and version-controlled way to create, modify, and share database tables and columns. Migrations are part of Laravel's schema building system and are used in conjunction with the schema builder to manage your database schema over time.
Key Features of Migrations
Creating Migrations: Migrations are created using the Artisan command-line tool. When you create a migration, Laravel generates a new migration file with a timestamp, which ensures that migrations are run in the correct order.
Create Migration:
php artisan make:migration create_posts_table
This command generates a migration file in the
database/migrations
directory with a name like2024_09_14_000000_create_posts_table.php
.
Migration Structure: Each migration file contains two primary methods:
up
anddown
.up
Method: This method is used to define the changes you want to make to the database, such as creating or modifying tables.Example:
public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->timestamps(); }); }
down
Method: This method is used to reverse the changes made in theup
method. It should undo the operations performed in theup
method.Example:
public function down() { Schema::dropIfExists('posts'); }
Running Migrations: Once you have defined your migrations, you can apply them to your database using the
migrate
Artisan command. This command runs all pending migrations that have not yet been applied.- Run Migrations:
php artisan migrate
This command executes the
up
method of each migration file that has not been run yet.- Run Migrations:
Rolling Back Migrations: You can roll back migrations to revert the database schema to a previous state. Laravel provides several options for rolling back migrations:
- Rollback the Last Batch:
php artisan migrate:rollback
This command rolls back the most recent batch of migrations.
- Rollback All Migrations:
php artisan migrate:reset
This command rolls back all migrations.
- Refresh Migrations:
php artisan migrate:refresh
This command rolls back all migrations and then re-applies them.
- Rollback the Last Batch:
Seeding: While migrations manage the structure of the database, seeding is used to populate the database with initial data. Laravel provides a
Seeder
class to handle database seeding.Create Seeder:
php artisan make:seeder PostsTableSeeder
Seeder Example:
public function run() { DB::table('posts')->insert([ 'title' => 'First Post', 'content' => 'Content of the first post', 'created_at' => now(), 'updated_at' => now(), ]); }
Run Seeders:
php artisan db:seed
This command runs all seeders defined in the
DatabaseSeeder
class.Migration Rollback and Re-Run: Sometimes you might want to roll back a specific number of migrations and then re-run them.
- Rollback a Specific Number:
php artisan migrate:rollback --step=1
This command rolls back the last batch of migrations, but only one step at a time.
- Rollback a Specific Number:
Migration Status: You can check the status of your migrations to see which ones have been run and which are pending.
- Check Migration Status:
php artisan migrate:status
- Check Migration Status:
Creating Indexes and Foreign Keys: Migrations allow you to define indexes and foreign key constraints for your tables, which are important for ensuring data integrity and improving query performance.
Add Indexes:
$table->index('column_name');
Add Foreign Keys:
$table->foreign('user_id')->references('id')->on('users');
Using Schema Builder: The Schema Builder provides a fluent API for creating and modifying database tables. It supports various operations like adding columns, modifying columns, and dropping columns.
Add Column:
Schema::table('posts', function (Blueprint $table) { $table->string('author')->after('title'); });
Drop Column:
Schema::table('posts', function (Blueprint $table) { $table->dropColumn('author'); });
Summary
Migrations in Laravel provide a structured way to manage your database schema using PHP code. They offer several key features:
- Creating Migrations: Define schema changes using the
make:migration
command. - Migration Structure: Consists of
up
anddown
methods for applying and rolling back changes. - Running Migrations: Use the
migrate
command to apply migrations. - Rolling Back Migrations: Revert changes using
migrate:rollback
,migrate:reset
, andmigrate:refresh
. - Seeding: Populate the database with initial data using seeders.
- Indexing and Foreign Keys: Define indexes and foreign key constraints.
- Schema Builder: Provides a fluent API for table modifications.
Migrations facilitate a smooth and controlled way to evolve your database schema as your application develops. They are essential for collaborative development and maintaining consistent database structure across different environments.