← All guides

Published · 7 min read

Migrations and the database in Laravel Rust, for Laravel developers

Writing migrations with the schema builder, backfilling data, why there's no down method, running migrations in production and squashing them, compared with Laravel PHP.

  • database
  • migrations
  • getting-started
On this page
  1. A migration, before and after
  2. Why there’s no down method
  3. Each migration runs in a transaction
  4. Changing a table and backfilling it
  5. Big tables and online indexes
  6. Migrations are part of the binary
  7. Running migrations
  8. Tables the framework needs
  9. Seeders and reference data
  10. Squashing old migrations
  11. Quick reference

Migrations in Laravel Rust will feel familiar: a timestamped file per change, a schema builder that writes the SQL for each database, a migrations table that records what has run, and laravel migrate to run the rest. Three things are different enough to learn up front: there’s no down method, each migration runs inside a transaction by default, and migrations are compiled into your app’s binary.

The migrations below are for a bike rental shop. Customers rent bikes by the hour and pay a deposit, and the shop later wants to see at a glance which rentals are still out.

The bike rental shop’s four migrations in order: create_rentals_table with a check that no deposit is negative, add_status_to_rentals_table which backfills the new column with db::query!, index_rentals_returned_at which builds the index concurrently on &AnyConnection outside a transaction, and drop_rentals_deposit_check, an undo written as a new migration. The others each run in a transaction. History only moves forward: there’s no down() and no migrate:rollback. migrations!(“database/migrations”) embeds the folder at compile time, so after cargo build –release a server runs ./app migrate –force with no source code.

A migration, before and after

In Laravel PHP:

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('rentals', function (Blueprint $table) {
            $table->id();
            $table->foreignId('bike_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained();
            $table->timestamp('starts_at');
            $table->timestamp('returned_at')->nullable();
            $table->integer('deposit_cents')->default(0);
            $table->timestamps();

            $table->index(['bike_id', 'starts_at']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('rentals');
    }
};

In Laravel Rust, generate the file with laravel make:migration create_rentals_table, then fill it in:

// database/migrations/2026_12_03_090000_create_rentals_table.rs
use laravel::db::{AnyTransaction, col};

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .create("rentals", |table| {
            table.id();
            table.foreign_id("bike_id").constrained().cascade_on_delete();
            table.foreign_id("user_id").constrained();
            table.timestamp("starts_at");
            table.timestamp("returned_at").nullable();
            table.integer("deposit_cents").default(0);
            table.timestamps();

            table.index(["bike_id", "starts_at"]);
            table.check("rentals_deposit_check", col("deposit_cents").ge(0));
        })
        .await
}

What changed:

  • One function, migrate. No class, no up and no down.
  • The method names are snake_case, but they’re the ones you know: foreign_id, constrained, cascade_on_delete, nullable, timestamps.
  • The schema call is awaited. Each schema operation runs when you .await it, so a second change is a second tx.schema()...await?.
  • A check constraint stops a negative deposit at the database level. It’s built from col(...) conditions rather than a SQL string.
  • make:migration reads the name. create_rentals_table scaffolds a new table with an id and timestamps; add_status_to_rentals_table scaffolds an alter("rentals", ..) block.

As in PHP, columns are NOT NULL unless you add .nullable(), and timestamp columns are written in UTC.

Why there’s no down method

Laravel Rust migrations are forward-only. There’s no down function and no migrate:rollback. The docs’ reasoning: rolling back a schema change in production is often unsafe, because dropping a table or column loses live data. To undo a change, you write a new migration that undoes it:

// database/migrations/2026_12_10_080000_drop_rentals_deposit_check.rs
use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .alter("rentals", |table| {
            table.drop_check("rentals_deposit_check");
        })
        .await
}

Locally, before a migration has been deployed, you can still edit it and rebuild your database from scratch with laravel migrate:fresh.

Tip: never edit or rename a migration that has run anywhere shared. Laravel tracks migrations by filename. An edited migration won’t run again, and a renamed one will run a second time.

Each migration runs in a transaction

Because migrate takes &mut AnyTransaction, Laravel wraps the migration and its row in the migrations table in one transaction. On PostgreSQL and SQLite, a migration that fails halfway leaves nothing behind: fix it and run migrate again.

MySQL and MariaDB commit automatically whenever a statement like CREATE TABLE runs, so a failed migration can leave its earlier statements applied. The advice for those databases is to keep each table change in its own migration file.

Changing a table and backfilling it

The shop wants a status column. Existing rentals that have a returned_at should start as returned. In Laravel PHP you might do this in two steps, or reach for DB::table()->update() in the migration. In Laravel Rust the migration can run queries too, and they join the same transaction:

// database/migrations/2026_12_05_100000_add_status_to_rentals_table.rs
use laravel::db::{self, AnyTransaction};

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .alter("rentals", |table| {
            table.enumeration("status", ["active", "returned"]).default("active");
        })
        .await?;

    db::query!("UPDATE rentals SET status = 'returned' WHERE returned_at IS NOT NULL")
        .update()
        .await?;

    Ok(())
}

db::query! is Laravel Rust’s raw SQL macro. To pass a Rust value into it, wrap the variable in braces (WHERE id = {id}) and it’s bound as a parameter, never pasted into the SQL. The SQL itself isn’t checked against your schema at compile time, so a misspelled column is a runtime error.

To change an existing column, redefine it and add .change(). As in recent Laravel PHP versions, the new definition replaces the old one completely, so repeat every modifier you want to keep:

tx.schema()
    .alter("bikes", |table| {
        table.string("frame_number").length(40).nullable().change();
    })
    .await?;

Big tables and online indexes

On PostgreSQL, a normal CREATE INDEX blocks writes until it’s built. .online() emits CREATE INDEX CONCURRENTLY instead, but PostgreSQL doesn’t allow that inside a transaction. For cases like this, a migration can take &AnyConnection instead of a transaction, and each statement commits as it runs:

// database/migrations/2026_12_06_020000_index_rentals_returned_at.rs
use laravel::db::AnyConnection;

pub async fn migrate(db: &AnyConnection) -> laravel::Result<()> {
    // A failed concurrent build leaves an invalid index, so clear it first.
    db.query("DROP INDEX CONCURRENTLY IF EXISTS rentals_returned_at_index")
        .statement()
        .await?;

    db.schema()
        .alter("rentals", |table| {
            table.index("returned_at").online();
        })
        .await?;

    Ok(())
}

If a non-transactional migration fails partway, the statements before the failure stay applied and the next run starts from the top, so write these to be safe to run twice. Other databases ignore .online(). On MySQL and MariaDB, .instant() and .lock(Lock::None) play a similar role for column changes.

Migrations are part of the binary

New apps register the migrations folder in src/app.rs:

Application::configure()
    .with_migrations(laravel::db::migrations!("database/migrations"))

The migrations! macro reads the folder at compile time and embeds every .rs file in it. That’s what lets a server run ./app migrate --force with no source code present. Two consequences:

  • Subfolders aren’t scanned. Keep every migration directly in database/migrations.
  • Cargo needs to know about new files. The app’s build.rs tells Cargo to watch the folder (cargo::rerun-if-changed=database/migrations). If you move the folder, update both paths.

Running migrations

Laravel PHP Laravel Rust
php artisan make:migration create_rentals_table laravel make:migration create_rentals_table
php artisan migrate laravel migrate
php artisan migrate:status laravel migrate:status
php artisan migrate:fresh --seed laravel migrate:fresh --seed
php artisan migrate:rollback No equivalent: write a new migration
php artisan migrate --database=reporting laravel migrate --database reporting
php artisan schema:dump --prune laravel schema:dump --prune
php artisan migrate --force on a server ./app migrate --force (the compiled binary)

migrate:status has two states worth knowing. pending, out of order means a migration with an earlier timestamp than one that already ran, typically from a merged branch; migrate still runs it. ran, not registered means the database recorded a migration whose file is gone, usually because it was renamed or deleted.

On a fresh machine, migrate offers to create a missing PostgreSQL, MySQL or MariaDB database for you (--force creates it without asking). SQLite creates its file when the connection URL ends in ?mode=rwc.

Tip: run migrations from one place. migrate takes no lock, so two servers running it at once can apply the same migration twice. Run it from a single deploy step. On Laravel Cloud, deploy commands already run once per deployment.

Tables the framework needs

The database cache, queue and session drivers need their own tables. Instead of copying their schema, a migration can hold just a macro:

// database/migrations/0001_01_01_000002_create_jobs_table.rs
laravel::queue::tables!();

There’s one each for the cache (laravel::cache::tables!()), sessions (laravel::session::table!()), feature flags and workflows. To change one of those tables later, replace the macro with the full migration from that feature’s docs.

Seeders and reference data

Seeders work much as in PHP: laravel db:seed, or laravel db:seed rentals for one seeder. Each db:seed run is wrapped in a single transaction, so a failing seeder rolls back the lot (with the same MySQL caveat as above).

The docs recommend putting data your app can’t run without, such as default roles or the list of bike types, in a migration, so it’s applied once to every database on every deploy. Seeders are for development and demo data.

Squashing old migrations

After a year of changes, every new database (including your test databases) has to run every migration. laravel schema:dump --prune writes the current schema to database/schema/<connection>-schema.sql and deletes the old .rs files. New apps embed that folder in the binary as well, so a server can still build a database from scratch. Dumping and loading uses the database’s own client (pg_dump and psql, mysqldump and mysql, or sqlite3), so install it wherever you run those commands, CI included.

Quick reference

Laravel PHP Laravel Rust
up() and down() One migrate function, forward only
Schema::create('t', fn ($table) => ...) tx.schema().create("t", |table| { ... }).await
Schema::table('t', ...) tx.schema().alter("t", ...)
$table->foreignId('x')->constrained() table.foreign_id("x").constrained()
->change() .change(), with every modifier repeated
DB::statement(...) in a migration db::query!(...) or tx.query(...), in the same transaction
public $withinTransaction = false; Take &AnyConnection instead of &mut AnyTransaction
Migration files read from disk Migrations compiled into the binary