Database: Migrations
- Introduction
- Generating migrations
- Migration structure
- Running migrations
- Registering migrations
- Squashing migrations
- Testing
Introduction
Migrations are like version control for your database. They let your team define the schema in code and share it. If you've ever had to tell a teammate to add a column to their local database after they pulled your changes, you've faced the problem that migrations solve.
Each migration is a Rust file in database/migrations that changes your schema with the schema builder or with SQL. Laravel records each migration it runs in a migrations table, so the migrate command runs only the ones that a database hasn't seen. Migrations compile into your application's binary, so a deployed server runs them without your source files.
Generating migrations
You may use the make:migration command to generate a migration. It writes a file in database/migrations whose name starts with the current UTC time, so your migrations run in the order you create them:
1laravel make:migration create_posts_table1laravel make:migration create_posts_table
make:migration infers the target table and operation from the migration name. Names such as create_posts_table or create_posts scaffold a new posts table with an id and timestamps, while names such as add_slug_to_posts_table scaffold an alter("posts", ..) block by extracting the table name after the final _to_, _from_, or _in_.
If the table cannot be inferred from the name, the generated migration starts empty. You can also specify the table explicitly with --create=posts for a new table or --table=posts for an existing one.
Migration structure
Each migration defines a single public migrate function that Laravel executes once per database. For example, this migration creates a posts table using the schema builder, generating the appropriate SQL for PostgreSQL, MySQL, MariaDB, or SQLite automatically:
1// database/migrations/2026_10_27_143000_create_posts_table.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("posts", |table| {7 table.id();8 table.foreign_id("user_id").constrained().cascade_on_delete();9 table.string("title");10 table.timestamp("published_at").nullable();11 table.timestamps();1213 table.index(["user_id", "published_at"]);14 })15 .await16}1// database/migrations/2026_10_27_143000_create_posts_table.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("posts", |table| {7 table.id();8 table.foreign_id("user_id").constrained().cascade_on_delete();9 table.string("title");10 table.timestamp("published_at").nullable();11 table.timestamps();1213 table.index(["user_id", "published_at"]);14 })15 .await16}
To see every column type, index, and constraint available on the table blueprint, check out the Schema Builder guide. Migrations may also execute queries with the same query API as the rest of your application, such as running db::query! to backfill a new column. Because migrate runs inside your application context, config() and container services are available as well.
When migrate accepts &mut AnyTransaction<'_>, Laravel wraps both your migration and its entry in the migrations table inside a single transaction. On PostgreSQL and SQLite, a failed migration rolls back cleanly without leaving partial schema changes behind, so you can fix the file and re-run migrate. Any query executed on the migration's connection automatically participates in the transaction.
MySQL and MariaDB issue an implicit commit whenever a DDL statement such as CREATE TABLE runs, so a failed migration on those engines can leave earlier statements applied. To avoid half-applied migrations on MySQL and MariaDB, keep each table change in its own migration file.
Framework tables
Some of Laravel's database drivers keep their data in tables you rarely change, such as the database cache store's cache table or the database queue driver's jobs table. Rather than copying each driver's schema into your application, you may create these tables with a migration that holds only the driver's macro:
1// database/migrations/0001_01_01_000001_create_cache_table.rs2laravel::cache::tables!();1// database/migrations/0001_01_01_000001_create_cache_table.rs2laravel::cache::tables!();
| Macro | Creates |
|---|---|
laravel::cache::tables!() |
The cache store's cache and cache_locks tables |
laravel::feature::table!() |
The feature flag store's features table |
laravel::queue::tables!() |
The queue's jobs, failed_jobs, job_batches, and job_batch_jobs tables |
laravel::session::table!() |
The session driver's sessions table |
laravel::workflow::tables!() |
The workflow store's five workflow_* tables |
Each macro defines the migration's migrate function and runs it in a transaction. If you'd like to change one of these tables later, such as renaming it or adding a column, replace the macro with the migration its guide shows and edit it. A migration that has already run doesn't run again, so make changes to a table that already exists in a new migration.
Changing a migration that has run
Migrations are forward-only: there is no down function or rollback command. Rolling back a schema change in production is often unsafe because dropping tables or columns risks losing live data, so modifying or undoing a previous migration in a live application is done by writing a new forward migration (such as dropping a column added earlier):
1// database/migrations/2026_11_02_090000_drop_posts_published_at.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .alter("posts", |table| {7 table.drop_column("published_at");8 })9 .await10}1// database/migrations/2026_11_02_090000_drop_posts_published_at.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .alter("posts", |table| {7 table.drop_column("published_at");8 })9 .await10}
Laravel tracks each migration by its filename (without .rs). Once a migration has run in a shared or production environment, never edit or rename it: an edited migration will not run again, and a renamed migration will run a second time.
During local development before your application has launched (or before a new migration has been deployed), you can modify the table's existing migration directly and run migrate:fresh to rebuild your local database from scratch.
Running a migration without a transaction
Some statements cannot execute inside a transaction, such as an online concurrent index build on PostgreSQL, and large data backfills often need to commit in batches rather than holding a single long-running transaction. To opt out of the automatic transaction, accept &AnyConnection instead of &mut AnyTransaction<'_>:
1// database/migrations/2026_10_27_160000_index_posts_slug.rs2use laravel::db::AnyConnection;34pub async fn migrate(db: &AnyConnection) -> laravel::Result<()> {5 // A failed concurrent build leaves an invalid index behind, so drop it before trying again.6 db.query("DROP INDEX CONCURRENTLY IF EXISTS posts_slug_index").statement().await?;78 db.schema()9 .alter("posts", |table| {10 table.index("slug").online();11 })12 .await?;1314 Ok(())15}1// database/migrations/2026_10_27_160000_index_posts_slug.rs2use laravel::db::AnyConnection;34pub async fn migrate(db: &AnyConnection) -> laravel::Result<()> {5 // A failed concurrent build leaves an invalid index behind, so drop it before trying again.6 db.query("DROP INDEX CONCURRENTLY IF EXISTS posts_slug_index").statement().await?;78 db.schema()9 .alter("posts", |table| {10 table.index("slug").online();11 })12 .await?;1314 Ok(())15}
Each statement commits immediately, and Laravel records the migration once migrate returns Ok(()). If a non-transactional migration fails partway through, statements that already ran remain applied and the next migrate run will execute the file from the top, so write these migrations to be idempotent (such as using IF EXISTS above).
Supporting several databases
While most applications target a single database engine, packages often ship migrations that need to run on whichever database an application uses. The schema builder translates portable schema definitions for you, whereas raw SQL is sent as written. When a migration requires engine-specific SQL, branch on tx.driver():
1// database/migrations/2026_10_28_090000_index_published_posts.rs2use laravel::db::{AnyTransaction, Driver};34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 // MySQL and MariaDB have no partial indexes, so they index every row...6 let sql = match tx.driver() {7 Driver::Postgres | Driver::Sqlite => {8 "CREATE INDEX posts_published_at_index ON posts (published_at) WHERE published_at IS NOT NULL"9 }10 Driver::MySql | Driver::MariaDb => {11 "CREATE INDEX posts_published_at_index ON posts (published_at)"12 }13 };1415 tx.query(sql).statement().await?;1617 Ok(())18}1// database/migrations/2026_10_28_090000_index_published_posts.rs2use laravel::db::{AnyTransaction, Driver};34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 // MySQL and MariaDB have no partial indexes, so they index every row...6 let sql = match tx.driver() {7 Driver::Postgres | Driver::Sqlite => {8 "CREATE INDEX posts_published_at_index ON posts (published_at) WHERE published_at IS NOT NULL"9 }10 Driver::MySql | Driver::MariaDb => {11 "CREATE INDEX posts_published_at_index ON posts (published_at)"12 }13 };1415 tx.query(sql).statement().await?;1617 Ok(())18}
Running migrations
To run every migration that hasn't run yet, use the migrate command:
1laravel migrate1laravel migrate
migrate creates the migrations table the first time, then runs the pending migrations in name order. If a migration fails, migrate stops and prints the database's error with the SQL that caused it. The migrations before it stay applied, so once you fix the failing migration, run migrate again to run the rest.
Creating a missing database
On a new machine, your configuration may point to a database that doesn't exist yet. On PostgreSQL, MySQL, and MariaDB, migrate and migrate:fresh prompt to create it automatically, or pass --force to create it without prompting. The configured database user must have permission to create databases.
SQLite creates the database file itself when the connection URL ends in ?mode=rwc, as the database guide shows.
Checking which migrations have run
migrate:status lists every migration and whether it has run. Each time you run migrate, the migrations it runs share one batch number:
1Migration Batch Status22026_09_01_120000_create_audits_table 1 ran, not registered32026_10_20_090000_create_teams_table 1 ran42026_10_21_110000_add_team_to_users pending, out of order52026_10_27_143000_create_posts_table 2 ran62026_10_28_101500_create_comments_table pending1Migration Batch Status22026_09_01_120000_create_audits_table 1 ran, not registered32026_10_20_090000_create_teams_table 1 ran42026_10_21_110000_add_team_to_users pending, out of order52026_10_27_143000_create_posts_table 2 ran62026_10_28_101500_create_comments_table pending
pending, out of order indicates a pending migration with an earlier timestamp than one that has already run (such as a migration merged from another branch); migrate will still execute it. ran, not registered indicates a migration recorded in the database that is no longer present in your application, usually because its file was renamed or deleted.
After you squash your migrations, the migrations in the schema dump no longer have files. migrate:status leaves them out of the list and counts them on one line below it instead, such as 42 migrations are squashed into the schema dump.
Rebuilding the database
During local development, you may want to rebuild your database from scratch. The migrate:fresh command drops every table and view in the database and then runs all migrations from the beginning:
1laravel migrate:fresh1laravel migrate:fresh
migrate:fresh drops all tables in the database, including tables created outside Laravel migrations, so avoid running it against a database shared with another application. On PostgreSQL, it also drops functions, procedures, custom types (including enums), domains, and sequences in the schemas on your search path while leaving installed extensions (such as citext) and their objects intact.
To seed the database immediately after rebuilding it, pass --seed to run your default seeder, or pass --seeder=posts to run a specific seeder:
1laravel migrate:fresh --seed1laravel migrate:fresh --seed
Choosing a connection
Migrations run against your default connection unless you pass --database to migrate, migrate:fresh, or migrate:status. That connection also becomes the default while the command runs, so raw db::query! calls inside migrations automatically target it as well:
1laravel migrate --database reporting1laravel migrate --database reporting
Running migrations in production
Because migrations can alter or drop production data, migrate and migrate:fresh ask for confirmation whenever APP_ENV is production or unset. Pass --force to run without prompting, such as in a deployment script (on a server, invoke your compiled binary directly rather than laravel):
1./app migrate --force1./app migrate --force
When deploying across multiple servers, run migrate from a single server or deployment step. Because migrate does not acquire a distributed lock, running it concurrently from multiple instances can cause two servers to execute the same migration at once.
When deploying on Laravel Cloud, deployment commands automatically run once per deployment, so you do not need to coordinate this yourself.
Registering migrations
New applications register their database/migrations directory in src/app.rs, so every migration you add there runs automatically:
1use laravel::Application;2use laravel::foundation::ApplicationBuilder;34pub fn configure() -> ApplicationBuilder {5 Application::configure()6 .with_migrations(laravel::db::migrations!("database/migrations"))7 // ...8}1use laravel::Application;2use laravel::foundation::ApplicationBuilder;34pub fn configure() -> ApplicationBuilder {5 Application::configure()6 .with_migrations(laravel::db::migrations!("database/migrations"))7 // ...8}
The migrations! macro reads that directory at compile time and embeds every .rs file directly inside it. Subdirectories are not scanned, so keep all migration files directly inside database/migrations.
Rebuilding after adding a migration
Cargo recompiles automatically when you edit an existing migration, but it does not detect newly added or deleted files on its own. Your application's build.rs instructs Cargo to watch the migrations directory:
1// build.rs2fn main() {3 println!("cargo::rerun-if-changed=database/migrations");4}1// build.rs2fn main() {3 println!("cargo::rerun-if-changed=database/migrations");4}
If you move your migrations to a different directory, update the path in both src/app.rs and build.rs.
Package migrations
Packages can ship their own migrations and register them in their service provider's register method. Laravel runs package migrations alongside your application's migrations in filename order:
1use laravel::container::Registrar;23fn register(&self, app: &mut Registrar) {4 app.migrations().add(laravel::db::migrations!("database/migrations"));5}1use laravel::container::Registrar;23fn register(&self, app: &mut Registrar) {4 app.migrations().add(laravel::db::migrations!("database/migrations"));5}
The path is relative to the package's Cargo.toml, and the package needs a build.rs watching database/migrations, as covered in the package development guide.
Squashing migrations
As you build your application, you may accumulate more and more migrations over time. This can lead to your database/migrations directory holding hundreds of migrations, which every new database (including your test databases) has to run. If you'd like, you may "squash" your migrations into a single SQL file. To get started, run the schema:dump command:
1laravel schema:dump23# Dump the current database schema and prune all existing migrations...4laravel schema:dump --prune1laravel schema:dump23# Dump the current database schema and prune all existing migrations...4laravel schema:dump --prune
When you run this command, Laravel writes a schema file to your application's database/schema directory named after the database connection, such as database/schema/postgres-schema.sql. The file contains your database's tables, indexes, and other objects, followed by the recorded rows from your migrations table. Pass --path to write the file to a different location, or --without-migration-data if you only want the schema without the migrations table rows.
Passing --prune deletes the .rs migration files in database/migrations while leaving package migrations untouched.
When you migrate a database with no recorded migrations yet, Laravel first executes the SQL statements in your connection's schema file and then runs any remaining migrations added since the dump. migrate:fresh does the same after dropping your tables. You may pass --schema-path to load a different file, or --schema-only to load the schema without running pending migrations:
1laravel migrate:fresh --schema-path=database/schema/archive-schema.sql1laravel migrate:fresh --schema-path=database/schema/archive-schema.sql
New applications embed database/schema into the compiled binary alongside your migrations so a server running only your binary can still build a new database after pruning. Both directories are registered in src/app.rs and watched in build.rs:
1// src/app.rs2pub fn configure() -> ApplicationBuilder {3 Application::configure()4 .with_migrations(laravel::db::migrations!("database/migrations"))5 .with_schema(laravel::db::schema!("database/schema"))6 // ...7}89// build.rs10fn main() {11 println!("cargo::rerun-if-changed=database/migrations");12 println!("cargo::rerun-if-changed=database/schema");13}1// src/app.rs2pub fn configure() -> ApplicationBuilder {3 Application::configure()4 .with_migrations(laravel::db::migrations!("database/migrations"))5 .with_schema(laravel::db::schema!("database/schema"))6 // ...7}89// build.rs10fn main() {11 println!("cargo::rerun-if-changed=database/migrations");12 println!("cargo::rerun-if-changed=database/schema");13}
If no embedded schema file exists for a connection, Laravel reads database/schema/<connection>-schema.sql from disk instead.
If your application's tests use a different database connection than local development, dump a schema file for that connection too so your tests can build their database from it:
1laravel schema:dump2laravel schema:dump --database=testing --prune1laravel schema:dump2laravel schema:dump --database=testing --prune
You should commit your schema files to source control so other developers on your team can quickly create your application's initial database structure.
Migration squashing supports PostgreSQL, MySQL, MariaDB, and SQLite, and uses the database's command-line client (pg_dump and psql, mysqldump and mysql, or sqlite3). Install the client on any machine that dumps or loads a schema, including CI and production servers. In-memory SQLite test databases load the schema file directly without the client.
Testing
To run your migrations automatically before each test, call refresh_database when building your test application. Laravel caches the migrated schema and re-runs migrations whenever a migration file changes. If you've squashed your migrations, Laravel loads the schema file first, then runs the migrations that came after it.