What are Migrations?
Migrations are version control for your database. Instead of manually creating tables and hoping everyone on your team has the same schema, migrations let you define your database structure in code. Everyone runs the same migrations, and everyone's database stays in sync.
Creating a Migration
Generate a new migration using Artisan:
php artisan make:migration create_users_table
This creates a file in database/migrations with two methods: up and down. The up method runs when you migrate, the down method runs when you rollback.
Defining Tables with Schema
Inside the up method, use the Schema facade to define your table structure:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
The down method simply drops the table:
public function down()
{
Schema::dropIfExists('users');
}
Column Types
Laravel gives you a rich set of column types:
$table->id();
$table->string('name');
$table->text('description');
$table->integer('age');
$table->boolean('is_active');
$table->decimal('price', 8, 2);
$table->date('birth_date');
$table->timestamp('email_verified_at');
$table->json('metadata');
$table->foreignId('user_id')->constrained();
The foreignId and constrained methods automatically create a foreign key constraint.
Running Migrations
Execute all pending migrations with:
php artisan migrate
Need to undo? Roll back the last batch of migrations:
php artisan migrate:rollback
Want a fresh start? Drop all tables and re-run everything:
php artisan migrate:fresh
The migrate:fresh command is great for development when you want to rebuild your database from scratch.
Adding Columns to Existing Tables
Migrations aren't just for creating tables. You can modify existing ones:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('phone')->nullable();
});
}
You can add columns, modify types, rename columns, and more. Each change is a separate migration file.