Laravel Migrations: How to Create a Database Migration
In this article
Laravel migrations are version control for your database schema. They let you define and modify tables (columns, indexes, foreign keys) in PHP code, then apply those changes to any environment with a single Artisan command. This guide walks through creating your first migration, running it, and rolling it back safely.
What You'll Need
- A Laravel project (version 8 or later recommended) installed locally.
- A database connection configured in your
.envfile (MySQL, PostgreSQL, SQLite, or SQL Server). - Composer installed to run Artisan commands.
- Basic familiarity with the command line and PHP syntax.
Step-by-Step
- Open your terminal in the root directory of your Laravel project.
- Generate a new migration file using the
make:migrationArtisan command. Name it descriptively, e.g.,php artisan make:migration create_products_table. This creates a file indatabase/migrations/with a timestamp prefix (e.g.,2025_01_01_000000_create_products_table.php). - Open the generated migration file in your code editor. You'll see two methods:
up()anddown(). Theup()method defines what changes to apply;down()reverses them. - Define the schema in the
up()method using Laravel's Schema builder. For a new table, useSchema::create('products', function (Blueprint $table) { ... }). Inside the closure, add columns. Example:Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name'); $table->text('description')->nullable(); $table->decimal('price', 8, 2); $table->timestamps(); });id()creates an auto-incrementing primary key;timestamps()addscreated_atandupdated_atcolumns. - Define the reverse in the
down()method. For a new table, useSchema::dropIfExists('products');. For altering an existing table, you'd reverse column changes (e.g.,dropColumn). - Run the migration with
php artisan migrate. This executes all pending migrations in order. You'll see output confirming each migration ran. - Verify the change in your database client (e.g., phpMyAdmin, TablePlus, or the command line) to ensure the table exists with the correct columns.
- Roll back if needed using
php artisan migrate:rollback. This runs thedown()method of the last batch of migrations. To roll back all migrations, usephp artisan migrate:reset. - Modify an existing table by generating a new migration, e.g.,
php artisan make:migration add_color_to_products_table --table=products. In theup()method, useSchema::table('products', function (Blueprint $table) { $table->string('color')->nullable(); });. Indown(), useSchema::table('products', function (Blueprint $table) { $table->dropColumn('color'); });.
Common Mistakes
- Forgetting the
down()method – always define it, even if it's just a dropIfExists, so you can roll back cleanly. - Using reserved words as table or column names (e.g., 'order', 'group'). Wrap them in backticks or use a different name.
- Not specifying a length for string columns – default is 255, but for fields like email, that's fine; for short codes, set a limit to avoid bloat.
- Running migrations on production without a backup – always backup before running migrations on a live database.
- Editing an already-run migration – never modify a migration that has been run on any environment; create a new one instead.
Tips
- Use
php artisan migrate:freshto drop all tables and re-run all migrations – great for local development, but never on production. - Use
--pretendflag:php artisan migrate --pretendshows the SQL that would be executed without running it, useful for review. - Always add
->nullable()for columns that may be empty to avoid errors when inserting incomplete data. - Use
foreignId()for foreign keys:$table->foreignId('user_id')->constrained();automatically creates an index and foreign key constraint. - Keep migrations small and focused – one change per migration makes rollback and debugging easier.
Troubleshooting
- Migration says 'table already exists' – run
php artisan migrate:statusto see which migrations have run. If a migration ran but the table was manually deleted, you can drop the row from themigrationstable or usemigrate:rollbackthen re-migrate. - SQL syntax error – check the column types. For example, using
stringfor a numeric field can cause issues; useintegerordecimalinstead. - Foreign key constraint fails – ensure referenced tables exist and the referenced column is indexed. Also check the order of migrations – the referenced table must be created first.
- Migration runs but no table appears – check your database connection in
.env. The default database might be different from what you're viewing. - Class not found – run
composer dump-autoloadto regenerate the autoloader after adding new migration files.
Frequently Asked Questions
Can I run a single migration file?
Yes. Use php artisan migrate --path=/database/migrations/2025_01_01_000000_create_products_table.php to run a specific file. This is useful for testing.
What's the difference between migrate:rollback and migrate:reset?
migrate:rollback rolls back the last batch of migrations (usually the most recent ones). migrate:reset rolls back all migrations, in reverse order.
How do I add a column to an existing table?
Create a new migration with --table=your_table and use Schema::table in the up() method to add the column. Never edit the original migration.
Can I use migrations without a database?
No, migrations require a database connection. However, you can use SQLite in-memory for testing by setting DB_CONNECTION=sqlite and DB_DATABASE=:memory: in your .env file.
What does php artisan migrate:status show?
It lists all migration files, along with whether they've been run (Ran) or not (Pending), helping you track what's applied.
Is it safe to run migrations on production?
Yes, if you've tested them locally and have a backup. Always run them during low-traffic periods and consider using --pretend first to review the SQL.