What Are Migrations? Migrations are like version control for your database schema. They allow you to define and modify database tables and their relationships using PHP code rather than raw SQL.
Creating a Migration: You can create a migration using the Artisan command make:migration
. This will generate a new migration file in the database/migrations
directory.
Example:
php artisan make:migration create_posts_table
This command creates a migration file named something like 2025_03_12_000000_create_posts_table.php
.
Defining the Table Structure: Open the generated migration file and define the structure of the database table inside the up()
method. Use the Schema builder to define columns and their types.
Example (Creating a Posts Table):
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id(); // Primary key
$table->string('title'); // String column
$table->text('content'); // Text column
$table->timestamps(); // Created_at and updated_at timestamps
});
}
In this example, we are creating a posts
table with an auto-incrementing primary key (id
), a title
, a content
, and timestamps
.
Running Migrations: Once the migration file is ready, you can apply the migration to your database by running the migrate
Artisan command.
Example:
php artisan migrate
This will create the posts
table in your database as defined in the migration.
Rolling Back Migrations: If you want to undo the last migration (or multiple migrations), you can use the migrate:rollback
Artisan command.
Example:
php artisan migrate:rollback
Modifying Existing Tables: If you need to modify an existing table (e.g., add new columns), you can create a new migration and use the Schema::table()
method.
Example (Adding a Column to the Posts Table):
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->string('author')->nullable();
});
}
Rolling Back All Migrations: To rollback all migrations (clear the entire database schema), use the migrate:reset
command.
Example:
php artisan migrate:reset
Migrations in Laravel are a powerful tool for managing your database schema. They allow you to create, modify, and rollback database tables in a version-controlled and organized manner. By following these simple steps, you can effectively manage your database structure throughout the lifecycle of your application.