Laravel Migrations: Streamline Database Schema Management
In this article
Laravel migrations let you define and version your database schema in plain PHP, so every change is tracked, repeatable, and shareable with your team. Instead of manually editing SQL or exporting dumps, you run a single command to create, alter, or roll back tables. This guide shows you how to use migrations effectively to keep your schema consistent across local, staging, and production environments.
What You'll Need
- A Laravel project (version 8 or newer recommended) set up with a database connection configured in your
.envfile. - Composer installed to run Laravel's Artisan commands.
- Basic familiarity with PHP and the command line.
Step-by-Step
- Understand the migration structure. Migrations live in
database/migrations. Each file contains a class with two methods:up()(applies changes) anddown()(reverses them). The filename includes a timestamp so Laravel knows the order to run them. - Create a new migration. Use Artisan to generate a migration file. Be descriptive—name it for what you're changing, e.g.,
php artisan make:migration create_posts_tableorphp artisan make:migration add_status_to_posts_table. Laravel will automatically guess the table name if you follow the convention. - Define the schema in the
up()method. Use the Schema builder to create or modify tables. For a new table, useSchema::create('posts', function (Blueprint $table) { ... }). Add columns with methods like$table->id(),$table->string('title'),$table->text('body'), and$table->timestamps(). For altering, useSchema::table('posts', function (Blueprint $table) { ... })and add or drop columns. - Write the
down()method to reverse changes. For a new table, useSchema::dropIfExists('posts'). For an altered table, reverse the changes—e.g., if you added a column, drop it with$table->dropColumn('status'). This ensures you can roll back cleanly. - Run the migration. Execute
php artisan migrateto apply all pending migrations. Laravel tracks which have run in themigrationstable. You'll see output confirming each migration ran. - Roll back when needed. To undo the last batch of migrations, run
php artisan migrate:rollback. To roll back all and re-run everything (common in development), usephp artisan migrate:fresh—this drops all tables and re-runs all migrations from scratch. - Use migration status to check. Run
php artisan migrate:statusto see which migrations have run and which are pending. This helps you keep track of what's applied on each environment. - Leverage advanced schema features. Use foreign keys, indexes, and constraints directly in migrations. For example,
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'). This keeps your schema logic centralized and versioned. - Use seeders for initial data. While not strictly part of migrations, seeders (
php artisan make:seeder) let you populate tables with test or default data. Run them withphp artisan db:seedorphp artisan migrate --seedto set up a fresh environment quickly. - Commit migration files to version control. Always commit your migration files to Git (or your VCS). This ensures every developer and server can recreate the exact schema by running
php artisan migrate.
Common Mistakes
- Editing existing migrations after they've been run. Once a migration is committed and run, never modify it. Other developers and production will have already applied it. Instead, create a new migration to make further changes.
- Forgetting the
down()method. If you skip it, rollback will fail. Always define a proper reverse operation. - Using
migrate:freshin production. This drops all data. Only use it in local development or when you intentionally want to reset a staging environment. - Not specifying a connection. If your app uses multiple databases, you can specify a connection in the migration by setting
$connectionproperty on the class. Forgetting this can cause migrations to run on the wrong database. - Ignoring column modifications. To change an existing column, you must use
$table->string('title')->change()—but this requires the doctrine/dbal package. Without it, changes silently fail.
Tips
- Use meaningful names. Name migrations by what they do, e.g.,
add_price_to_products_table—this makes the history clear. - Keep migrations small. One logical change per migration. It's easier to debug and roll back.
- Use
migrate:statusbefore deploying. Ensure all migrations are applied in the right order. - Use
--pretendto see SQL. Runphp artisan migrate --pretendto output the SQL that would be executed without actually running it. Useful for checking. - Set up CI to run migrations. In your continuous integration pipeline, run
php artisan migrate --force(to bypass confirmation in production) to catch schema issues early. - Use schema factories for test data. Combine migrations with model factories to generate realistic test data quickly.
Troubleshooting
- Migration fails with a SQL error. Check the error message—it often points to a syntax issue or a missing column. Verify your table and column names, and ensure you're using the correct data types. If you're altering a column, confirm you've installed
doctrine/dbalvia Composer. - Migration runs but table isn't created. Check if you're using the correct database connection. Run
php artisan config:clearand verify your.envsettings. Also, ensure the migration file is in thedatabase/migrationsdirectory. - Rollback doesn't work. If
down()is missing or has an error, the rollback will fail. Fix the method and try again. If you're stuck, you can manually delete the row from themigrationstable and drop the table via SQL—but only as a last resort. - Foreign key constraint fails. Ensure the referenced table and column exist. Also, check the order of migrations—the referenced table must be created before the referencing table. If needed, reorder files by renaming timestamps.
- Column change doesn't take effect. Remember to use
->change()and have doctrine/dbal installed. Also, some databases (like SQLite) don't support column modifications—you may need to recreate the table.
Frequently Asked Questions
Can I use migrations with an existing database?
Yes. You can create a migration that adds new tables or alters existing ones. For an existing table, use Schema::table to modify it. You don't need to recreate the whole schema.
How do I rename a column?
Use $table->renameColumn('old', 'new') in a migration. This requires doctrine/dbal for most databases.
What's the difference between migrate and migrate:fresh?
migrate runs only pending migrations. migrate:fresh drops all tables and re-runs all migrations from scratch—it's destructive and wipes data.
Can I run migrations on a specific database connection?
Yes, use php artisan migrate --database=connection_name. You can also set a $connection property on the migration class.
How do I seed data after migrating?
Run php artisan db:seed or add --seed to the migrate command, e.g., php artisan migrate --seed.
What if I need to change a migration that's already been run?
Don't edit it. Create a new migration that makes the additional changes. This preserves the history and ensures consistency across environments.