Laravel migrations that can be re-run safely

Published 2026-11-06

The problem with trusting the migration table

Laravel records which migrations have run in a table, and in a tidy world that is enough. In a real one, a deploy is interrupted halfway, a column is added by hand during an incident, or a database is restored from a backup taken before a migration was recorded. The next deploy then tries to create something that already exists and the whole release stops with a duplicate column error.

The fix is cheap: make each migration idempotent, meaning that running it twice leaves the database in the same state as running it once. The schema builder already gives you the tools, hasTable and hasColumn, and a migration that wraps its changes in those checks turns a release-stopping error into a harmless no-op.

Guard every change

Before creating a table, check that it is absent. Before adding a column, check that the table exists and the column does not. Before adding an index, check the index. The checks add a few lines and remove an entire category of deploy failures.

Be careful with the after() modifier when adding a column. It names a column that must exist, and on a database that drifted from the expected shape it fails. Unless column order truly matters to you, which in a relational database it almost never does, leave it out.

Write a down() you have actually run

A rollback method that has never been executed is a guess. Run migrate and then rollback against a throwaway database at least once, and look at the result. Dropping a column in down() destroys data, so decide consciously whether the rollback should drop it or simply leave it, and say so in a comment.

For changes that cannot be undone, such as converting data in place, write the down() to throw a clear exception instead of pretending. A failing rollback that explains itself is better than a silent one that leaves the data half converted.

Separate schema from data

Migrations change structure. Seeding reference data or backfilling values belongs in a seeder or a one-off command that uses firstOrCreate or updateOrCreate, so it can be repeated without duplicating rows. Mixing the two makes a migration slow, hard to roll back and risky on a large table.

On big tables, think about locking. Adding a column with a default can rewrite the table on some engines and versions. Test on a copy of production-sized data and schedule the change for a quiet moment, rather than discovering the lock during peak traffic.

A short checklist

  • Wrap creates and alters in hasTable and hasColumn checks.
  • Avoid after() unless order matters.
  • Run up, down and up again on a scratch database.
  • Keep data backfills out of schema migrations.
  • Take a backup before touching a live database and know how to restore it.

© 2026 The Good Fellas