跳至正文

Database: Migrations ​

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 Go function 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:

shell
laravel make:migration create_posts_table

The command also adds the new migration to the All list in database/migrations/migrations.go, which is how your application finds it. To learn more about that list, check out the section on registering migrations.

make:migration uses the migration's name to guess the table and whether the migration creates it. Names such as create_posts_table or create_posts start the migration with a new posts table that has an id and timestamps, while names such as add_slug_to_posts_table start it with an empty schema.Alter of posts, taking the table name after the final _to_, _from_, or _in_.

If the name doesn't say which table, the generated migration starts empty. You may also name the table yourself, with --create=posts for a new table or --table=posts for an existing one:

shell
laravel make:migration add_featured_flag --table=posts

Migration structure ​

Each migration is a function that takes a context and returns an error, and Laravel calls it once on each database. make:migration names the function after the migration, so create_posts_table becomes createPostsTable. For example, this migration creates a posts table with the schema builder, which writes the right SQL for PostgreSQL, MySQL, MariaDB, or SQLite:

go
// database/migrations/2026_11_10_120000_create_posts_table.go
package migrations

import (
	"context"

	"go.laravel.com/schema"
)

func createPostsTable(ctx context.Context) error {
	return schema.Create(ctx, "posts", func(table *schema.Blueprint) {
		table.ID()
		table.ForeignID("user_id").Constrained().CascadeOnDelete()
		table.String("title")
		table.Timestamp("published_at").Nullable()
		table.Timestamps()

		table.Index("user_id", "published_at")
	})
}

To see every column type, index, and constraint you may add to a table, check out the schema builder guide. Migrations may also query the database as the rest of your application does, with db.Exec, the query builder, or models, such as to fill in a new column for existing rows.

Laravel runs each migration and its entry in the migrations table in a single transaction, which the migration's ctx carries. Every schema builder call, query, and model write that you run with ctx joins that transaction. On PostgreSQL and SQLite, a failed migration rolls back cleanly without leaving partial schema changes behind, so you can fix the migration and run migrate again.

MySQL and MariaDB commit the transaction whenever they run a statement that changes a table, such as CREATE TABLE, so a failed migration on those databases can leave its earlier statements applied. To avoid half-applied migrations on MySQL and MariaDB, keep each table change in its own migration.

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 writing out each driver's columns in your application, you may pass the driver's migration helper directly as Run in database/migrations/migrations.go:

go
// database/migrations/migrations.go
package migrations

import (
	"go.laravel.com/cache"
	"go.laravel.com/db"
	"go.laravel.com/queue"
)

var All = []db.Migration{
	{Name: "0001_01_01_000001_create_cache_table", Run: cache.CreateTables},
	{Name: "0001_01_01_000002_create_jobs_table", Run: queue.CreateTables},
}
HelperCreates
cache.CreateTablesThe cache store's cache and cache_locks tables
feature.CreateTableThe feature flag store's features table
queue.CreateTablesThe queue's jobs, failed_jobs, job_batches, and job_batch_jobs tables
session.CreateTableThe session driver's sessions table
workflow.CreateTablesThe workflow store's five workflow_* tables

If you'd like to customize one of these tables later, such as adding an index or a column, write a new forward migration after it has run.

Changing a migration that has run ​

Migrations only run forward: there's 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. To change or undo what an earlier migration did in a live application, write a new migration, such as one that drops a column an earlier migration added:

go
// database/migrations/2026_11_12_090000_drop_posts_published_at.go
func dropPostsPublishedAt(ctx context.Context) error {
	return schema.Alter(ctx, "posts", func(table *schema.Blueprint) {
		table.DropColumn("published_at")
	})
}

Laravel tracks each migration by the Name its entry in All gives it, which make:migration sets to the file's name without .go. Once a migration has run in a shared or production environment, never edit or rename it: an edited migration won't 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 may edit 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 can't run inside a transaction, such as an Online index build on PostgreSQL, and a large backfill often needs to commit in batches rather than hold one long transaction open. To run a migration without the automatic transaction, set NoTransaction on its entry in All:

go
// database/migrations/migrations.go
var All = []db.Migration{
	// ...
	{Name: "2026_11_10_160000_index_posts_slug", Run: indexPostsSlug, NoTransaction: true},
}

The migration's ctx then carries the connection pool instead of a transaction. For example, this migration builds an index on PostgreSQL without blocking writes to posts:

go
// database/migrations/2026_11_10_160000_index_posts_slug.go
func indexPostsSlug(ctx context.Context) error {
	// A failed concurrent build leaves an invalid index behind, so drop it before trying again.
	if _, err := db.Exec(ctx, "drop index concurrently if exists posts_slug_index"); err != nil {
		return err
	}

	return schema.Alter(ctx, "posts", func(table *schema.Blueprint) {
		table.Index("slug").Online()
	})
}

Each statement commits immediately, and Laravel records the migration once the function returns nil. If a migration without a transaction fails partway through, the statements that already ran stay applied, and the next migrate runs the whole migration again from the top. Write these migrations so they're safe to run twice, such as with the if exists above.

Supporting several databases ​

While most applications target a single database, packages often ship migrations that need to run on whichever database an application uses. The schema builder translates portable schema definitions for you, but Laravel sends the SQL you pass to db.Exec exactly as you wrote it. When a migration needs SQL for one database, check the connection's dialect with db.From(ctx).Dialect():

go
// database/migrations/2026_11_11_090000_index_published_posts.go
func indexPublishedPosts(ctx context.Context) error {
	var query string

	switch db.From(ctx).Dialect() {
	case db.Postgres, db.SQLite:
		query = "create index posts_published_at_index on posts (published_at) " +
			"where published_at is not null"
	case db.MySQL, db.MariaDB:
		// MySQL and MariaDB have no partial indexes, so they index every row.
		query = "create index posts_published_at_index on posts (published_at)"
	}

	_, err := db.Exec(ctx, query)

	return err
}

Running migrations ​

To run every migration that hasn't run yet, use the migrate command:

shell
laravel 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, DATABASE_URL may name a database that doesn't exist yet. On PostgreSQL, MySQL, and MariaDB, migrate and migrate:fresh offer to create it, or you may pass --force to create it without asking. Laravel connects with the URL's credentials, so the URL's user must have permission to create databases.

SQLite creates the database file itself the first time your application opens it, as long as the file's directory exists, 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:

text
Migration                                Batch  Status
2026_09_01_120000_create_audits_table    1      ran, not registered
2026_10_20_090000_create_teams_table     1      ran
2026_10_21_110000_add_team_to_users             pending, out of order
2026_10_27_143000_create_posts_table     2      ran
2026_10_28_101500_create_comments_table         pending

pending, out of order marks a pending migration that's older than one that has already run, such as a migration merged from another branch, and migrate will still run it. ran, not registered marks a migration that the database has run but All no longer lists, usually because you renamed or deleted it.

When database/migrations has a migration file that All doesn't list, such as one you added by hand, migrate:status warns you about it, because migrate won't run it until you add it to All.

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, then runs all of your migrations from the beginning. 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:

shell
laravel migrate:fresh

migrate:fresh drops every table in the database, including tables that no migration created, so don't run it against a database that another application shares.

To fill the database with rows right after rebuilding it, pass --seed to run your seeders, or pass --seeder=posts to run one seeder by name:

shell
laravel migrate:fresh --seed

Choosing a connection ​

Migrations run on your default database, the one DATABASE_URL names, unless you pass --database to migrate, migrate:fresh, or migrate:status with the name of another connection, such as a reporting database:

shell
laravel migrate --database reporting

The migration's ctx carries that connection, so the schema builder and db.Exec calls inside your migrations target it as well. Each connection keeps its own migrations table, so each database records which migrations it has run.

Running migrations in production ​

Because migrations can change or drop production data, migrate and migrate:fresh ask for confirmation whenever APP_ENV is production or isn't set. Pass --force to run without the prompt, such as in a deploy script. Without --force, a deploy script that has no terminal to answer the prompt fails rather than migrating. On a server, run your compiled binary directly rather than laravel:

shell
./app migrate --force

When you deploy to several servers, run migrate from a single server or deploy step. If two servers do run it at once, migrate holds a database lock while it runs, so each migration still runs only once.

说明

When you deploy on Laravel Cloud, put ./app migrate --force in your deploy commands. Cloud runs them once per deploy, however many instances you have, so you don't need to coordinate this yourself.

Registering migrations ​

Go can't discover the functions in a directory at run time, so database/migrations/migrations.go lists your migrations in All, and make:migration adds each new migration to the end of the list:

go
// database/migrations/migrations.go
package migrations

import "go.laravel.com/db"

// All are the application's migrations, which migrate runs in name order.
var All = []db.Migration{
	{Name: "2026_11_10_120000_create_posts_table", Run: createPostsTable},
	{Name: "2026_11_10_160000_index_posts_slug", Run: indexPostsSlug, NoTransaction: true},
}

New applications pass the list to Laravel in bootstrap/app.go, so every migration in All runs automatically:

go
return laravel.Options{
	// ...
	Migrations: migrations.All,
}

migrate runs the migrations in name order, whatever their order in All, so a migration you merge from another branch may go anywhere in the list. If two migrations share a name, migrate refuses to run.

Package migrations ​

Packages may ship their own migrations, such as the table a billing package stores invoices in, and add them from their Register method. Laravel runs package migrations alongside your application's migrations, in name order:

go
func (b *Billing) Register(app *laravel.Registrar) error {
	app.Migrations(migrations.All...)

	return nil
}

The package keeps its migrations in a migrations package of its own, which has an All list like your application's. To learn more, check out the package development guide's section on migrations.

Squashing migrations ​

As you build your application, your database/migrations directory may collect 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 with the schema:dump command:

shell
laravel schema:dump

# Dump the database schema and delete the migrations it holds...
laravel schema:dump --prune

When you run this command, Laravel writes your database's schema and the rows from its migrations table to database/schema/<connection>-schema.sql. For the default connection, this file is database/schema/default-schema.sql (or <name>-schema.sql when DB_CONNECTION selects a named connection). Pass --database to dump a different connection, --path to write the file elsewhere, or --without-migration-data to omit the migrations table rows.

Passing --prune deletes the migration files in database/migrations (leaving migrations.go and any _test.go files in place) and empties All so the package continues to compile.

When you run migrate on a database whose migrations table is empty, such as a new database or after migrate:fresh, Laravel first loads your connection's schema file and then runs any migrations added since the dump. migrate:status omits squashed migrations from the table and summarizes them on one line:

text
Migration                              Batch  Status
2026_11_20_090000_add_avatar_to_users         pending

42 migrations are squashed into the schema dump.

New applications embed database/schema in database/schema/schema.go and pass it to Laravel in bootstrap/app.go so a server running only your compiled binary can still build a new database from the dump:

go
return laravel.Options{
	// ...
	Migrations: migrations.All,
	Schema:     schema.Dumps,
}

Rebuild the binary after dumping the schema, as you would after adding a migration. If no embedded dump exists for a connection, Laravel reads database/schema/<connection>-schema.sql from disk instead. You may pass --schema-path to migrate or migrate:fresh to load a specific file, or --schema-only to load the schema without running pending migrations.

You should commit your schema file to source control so other developers on your team can quickly create your application's initial database structure.

Your tests load the default connection's schema file too. If your tests use a different database driver than local development, such as SQLite while you develop on PostgreSQL, define a dedicated connection in bootstrap/app.go so it gets its own schema file:

go
// bootstrap/app.go
func configure(cfg *config.Config, env *config.Env) {
	cfg.Database.Connections = map[string]config.Connection{
		"testing": {
			URL: env.String("TESTING_DATABASE_URL", "sqlite:database/testing.sqlite"),
		},
	}
}

Select that connection in .env.testing:

ini
DB_CONNECTION=testing

Then dump both connections so laraveltest.RefreshDatabase loads database/schema/testing-schema.sql into each test database:

shell
laravel schema:dump
laravel migrate --database=testing
laravel schema:dump --database=testing --prune

警告

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 before your tests, pass laraveltest.RefreshDatabase when building your test client, as new applications do. Laravel keeps the migrated test database between runs and rebuilds it from your schema file and every migration whenever your code or schema file changes, so you don't need to migrate the test database yourself.