The Wild

Laravel Migrations: How to Create a Database Migration

· 4 min read · Mammals

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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 .env file (MySQL, PostgreSQL, SQLite, or SQL Server).
  • Composer installed to run Artisan commands.
  • Basic familiarity with the command line and PHP syntax.

Step-by-Step

  1. Open your terminal in the root directory of your Laravel project.
  2. Generate a new migration file using the make:migration Artisan command. Name it descriptively, e.g., php artisan make:migration create_products_table. This creates a file in database/migrations/ with a timestamp prefix (e.g., 2025_01_01_000000_create_products_table.php).
  3. Open the generated migration file in your code editor. You'll see two methods: up() and down(). The up() method defines what changes to apply; down() reverses them.
  4. Define the schema in the up() method using Laravel's Schema builder. For a new table, use Schema::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() adds created_at and updated_at columns.
  5. Define the reverse in the down() method. For a new table, use Schema::dropIfExists('products');. For altering an existing table, you'd reverse column changes (e.g., dropColumn).
  6. Run the migration with php artisan migrate. This executes all pending migrations in order. You'll see output confirming each migration ran.
  7. Verify the change in your database client (e.g., phpMyAdmin, TablePlus, or the command line) to ensure the table exists with the correct columns.
  8. Roll back if needed using php artisan migrate:rollback. This runs the down() method of the last batch of migrations. To roll back all migrations, use php artisan migrate:reset.
  9. Modify an existing table by generating a new migration, e.g., php artisan make:migration add_color_to_products_table --table=products. In the up() method, use Schema::table('products', function (Blueprint $table) { $table->string('color')->nullable(); });. In down(), use Schema::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:fresh to drop all tables and re-run all migrations – great for local development, but never on production.
  • Use --pretend flag: php artisan migrate --pretend shows 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:status to see which migrations have run. If a migration ran but the table was manually deleted, you can drop the row from the migrations table or use migrate:rollback then re-migrate.
  • SQL syntax error – check the column types. For example, using string for a numeric field can cause issues; use integer or decimal instead.
  • 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-autoload to 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.