DEV Community

Cover image for I Broke One Laravel Migration on MySQL, PostgreSQL and SQLite. What MigrationFailed in 13.42 Changes
Hafiz
Hafiz

Posted on Originally published at hafiz.dev

I Broke One Laravel Migration on MySQL, PostgreSQL and SQLite. What MigrationFailed in 13.42 Changes

Originally published at hafiz.dev


You fix the duplicate data, run php artisan migrate again, and Laravel answers with Duplicate column name 'slug'. The migration failed the first time, so Laravel never recorded it. But half of it ran anyway, and now that half blocks the retry.

Laravel 13.42 added a MigrationFailed event for this exact moment (PR #62342, from Jack Bayliss). It fires when a migration throws and carries the exception. The release write-up on Laravel News suggests using it to alert your team before users hit a half-applied schema.

So which databases actually leave one behind? I ran the same failing migration on MySQL 8.4.13, PostgreSQL 17.12 and SQLite 3.53.4 (the version bundled with PHP 8.4 on my Mac), all on Laravel 13.42.0. They didn't all leave the same mess behind.

The migration that fails halfway

It's the classic slug migration. Add a nullable column, backfill it, then add the unique index:

public function up(): void
{
    Schema::table('products', function (Blueprint $table) {
        $table->string('slug')->nullable()->after('name');
    });

    DB::table('products')->orderBy('id')->each(function ($product) {
        DB::table('products')
            ->where('id', $product->id)
            ->update(['slug' => Str::slug($product->name)]);
    });

    Schema::table('products', function (Blueprint $table) {
        $table->unique('slug');
    });
}
Enter fullscreen mode Exit fullscreen mode

The products table has three rows: Blue Mug, Red Kettle, and a second Blue Mug (two sizes, same name). The backfill writes blue-mug twice, so the index can't be built. That's the failure, on purpose. It's also a realistic one, because a duplicate like this shows up in production data and almost never in a seeded local database.

MySQL keeps the column, and the retry fails

The first run, with the stack trace trimmed:

 2026_11_14_000002_add_slug_to_products_table .. 32.09ms FAIL

   Illuminate\Database\UniqueConstraintViolationException

  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'blue-mug'
  for key 'products.products_slug_unique' (Connection: mysql, ... SQL: alter table
  `products` add unique `products_slug_unique`(`slug`))
Enter fullscreen mode Exit fullscreen mode

Then I checked the table and the migrations table:

Schema::hasColumn('products', 'slug');
DB::table('products')->orderBy('id')->pluck('slug');
collect(Schema::getIndexes('products'))->pluck('name');
DB::table('migrations')->where('migration', 'like', '%add_slug%')->exists();
Enter fullscreen mode Exit fullscreen mode
slug column: true
slugs: ["blue-mug","red-kettle","blue-mug"]
indexes: ["primary"]
recorded: false
Enter fullscreen mode Exit fullscreen mode

The column is there. The backfilled slugs are there. The index isn't, and Laravel has no record that any of it happened. So I renamed the second product to Blue Mug Large and ran migrate again:

 2026_11_14_000002_add_slug_to_products_table .. 7.97ms FAIL

   Illuminate\Database\QueryException

  SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'slug'
  (Connection: mysql, ... SQL: alter table `products` add `slug` varchar(255) null after `name`)
Enter fullscreen mode Exit fullscreen mode

The data is fixed. The migration still can't run, because its first statement now collides with its own leftovers. From here you drop the column by hand, edit the migration, or insert a fake row into migrations. None of those belong in a deploy.

PostgreSQL rolls the whole thing back

Same migration, same three rows, same failure on the unique index. The state afterwards:

slug column: false
indexes: ["products_pkey"]
recorded: false
Enter fullscreen mode Exit fullscreen mode

No column, no slugs, no record. After the same rename, the retry just worked:

 2026_11_14_000002_add_slug_to_products_table .. 12.95ms DONE
Enter fullscreen mode Exit fullscreen mode

It's the behaviour I'd assumed I was getting everywhere.

And SQLite?

New Laravel apps have used SQLite as the default database since Laravel 11, so plenty of local setups run this exact path.

View the interactive component on hafiz.dev

slug column: true
slugs: ["blue-mug","red-kettle","blue-mug"]
indexes: ["primary"]
recorded: false
Enter fullscreen mode Exit fullscreen mode

SQLite kept everything MySQL kept. The retry failed the same way too, with duplicate column name: slug. And it isn't because SQLite can't do better. Wrapped in a transaction, SQLite rolled this same migration back completely (that test is further down). Laravel just never opens the transaction.

View the interactive component on hafiz.dev

Where the difference comes from

The answer is a few lines in Illuminate\Database\Migrations\Migrator::runMigration(), as of 13.42:

try {
    $this->getSchemaGrammar($connection)->supportsSchemaTransactions()
        && $migration->withinTransaction
            ? $connection->transaction($callback)
            : $callback();
} catch (Throwable $e) {
    $this->fireMigrationEvent(new MigrationFailed($migration, $method, $name, $e));

    throw $e;
}
Enter fullscreen mode Exit fullscreen mode

supportsSchemaTransactions() reads a $transactions property on the schema grammar. It's true in PostgresGrammar and SqlServerGrammar. Every other grammar keeps the base class default, which is false.

For MySQL that's the honest answer. Every ALTER TABLE causes an implicit commit, so a transaction around the migration wouldn't hold anyway. MariaDB gets the same treatment, because MariaDbGrammar extends MySqlGrammar.

SQLite is different. The wrapping arrived in Laravel 5.3 with PR #15780, and that PR only switched it on for PostgreSQL. Its author said they couldn't test SQL Server and weren't sure SQLite fully supported alter table inside a transaction. SQL Server got the flag later. SQLite never did.

So on MySQL and SQLite, each statement runs on its own and commits as it goes. The ALTER TABLE commits. Each UPDATE commits. The failing index takes nothing back with it.

What MigrationFailed actually gives you

The event fires in that catch block, and where it sits explains how it behaves:

  • On PostgreSQL it fires after the rollback. $connection->transaction() has already rolled back and rethrown by the time the catch runs. A listener I added there saw no slug column on PostgreSQL.
  • The exception is rethrown after the listeners run. So migrate still exits with 1, and a deploy script running with set -e still stops.
  • It fires for down as well. migrate:rollback goes through the same runMigration(), with $event->method set to down.

What it carries is the migration instance, the method, the file name and the exception. Like the slow job alerts from 13.40, it reports the moment and leaves the diagnosis to you. It doesn't tell you whether anything was rolled back, or which statements already ran. On MySQL, that second part is what you need to recover.

A listener that says what got left behind

This one records schema statements while a migration runs, and logs them only if they survived the failure:

use Illuminate\Database\Events\MigrationFailed;
use Illuminate\Database\Events\MigrationStarted;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

public function boot(): void
{
    if (! $this->app->runningInConsole()) {
        return;
    }

    $statements = [];

    Event::listen(function (MigrationStarted $event) use (&$statements) {
        $statements = [];
    });

    DB::listen(function (QueryExecuted $query) use (&$statements) {
        if (preg_match('/^\s*(alter|create|drop|rename)\b/i', $query->sql)) {
            $statements[] = $query->sql;
        }
    });

    Event::listen(function (MigrationFailed $event) use (&$statements) {
        $connection = DB::connection($event->migration->getConnection());

        $rolledBack = $event->migration->withinTransaction
            && $connection->getSchemaGrammar()->supportsSchemaTransactions();

        Log::critical("Migration [{$event->name}] failed", [
            'connection' => $connection->getName(),
            'rolled_back' => $rolledBack,
            'already_applied' => $rolledBack ? [] : $statements,
            'error' => $event->exception->getMessage(),
        ]);
    });
}
Enter fullscreen mode Exit fullscreen mode

The rolled_back check copies the Migrator's own condition, so it also covers a migration that sets $withinTransaction = false. QueryExecuted only fires for statements that succeeded, so the failing one never lands in the list. Here's what it logged on each database, with the error message cut:

mysql   {"connection":"mysql","rolled_back":false,"already_applied":["alter table `products` add `slug` varchar(255) null after `name`"]}
pgsql   {"connection":"pgsql","rolled_back":true,"already_applied":[]}
sqlite  {"connection":"sqlite","rolled_back":false,"already_applied":["alter table \"products\" add column \"slug\" varchar"]}
Enter fullscreen mode Exit fullscreen mode

I left the backfill UPDATEs out on purpose. They committed too, but one line per row is noise in an alert, and the column they wrote to is already in the list. Send the same context to Slack or wherever your alerts go. The log channel is just what I tested with.

Should the listener put the app down?

The Laravel News example calls Artisan::call('down') from the listener. I wouldn't do that by default.

On PostgreSQL there's nothing half-applied, so maintenance mode protects nobody. On MySQL, look at what's actually left here: one extra nullable column. The code that's still running has never heard of it and will keep working. Taking the site down turns a quiet problem into an outage, in the middle of a deploy that already has enough moving parts (your queue workers get a SIGTERM in that same window).

The case for down is a migration that drops or renames something before it fails. The running code does read that column, and it will start throwing. The already_applied list tells you which case you're in, which is a better trigger than "any migration failed".

Make MySQL fail at a clean boundary

A migration only gets a row in migrations after up() returns. So the fix on MySQL is to put each statement that can fail in its own migration:

2026_11_14_000002_add_slug_column_to_products_table.php
2026_11_14_000003_backfill_product_slugs.php
2026_11_14_000004_add_unique_index_to_product_slugs.php
Enter fullscreen mode Exit fullscreen mode

Same code as before, split three ways. The same three rows on MySQL:

 2026_11_14_000002_add_slug_column_to_products_table .. 16.21ms DONE
 2026_11_14_000003_backfill_product_slugs .. 7.91ms DONE
 2026_11_14_000004_add_unique_index_to_product_slugs .. 13.32ms FAIL
Enter fullscreen mode Exit fullscreen mode

Now the failure sits on a recorded boundary. The backfill already ran, so the fix has to update the slug as well as the name. After that, migrate ran only the index:

 2026_11_14_000004_add_unique_index_to_product_slugs .. 32.57ms DONE
Enter fullscreen mode Exit fullscreen mode

No hand-dropped columns, no fake rows in migrations. Just a data fix and a retry.

On SQLite you have a second option, because SQLite can roll back DDL. I wrapped the original single migration in a transaction myself:

public function up(): void
{
    DB::transaction(function () {
        // the same three steps as before
    });
}
Enter fullscreen mode Exit fullscreen mode

On SQLite it failed on the index and left no slug column behind. On MySQL the same wrapper changed nothing, and the column was still there. I only tested this migration, so try your own riskier SQLite migrations the same way before you rely on it.

You'll also see Schema::hasColumn() guards suggested for this. They make a retry pass, but they also hide that the schema drifted, so I'd keep them as a last resort rather than the plan. If you squash migrations, the schema:dump --prune post covers what happens to files like these later.

FAQ

Does a failed migration get recorded in the migrations table?

No. Laravel writes the row only after up() returns. In my tests the failed migration had no row on any of the three databases, which is exactly why MySQL and SQLite end up stuck: the schema changed, but the record says it didn't.

Does MigrationFailed fire during migrate:rollback?

Yes. Rollbacks run through the same runMigration() method, so a down() that throws fires the event with $event->method set to down.

Is MariaDB the same as MySQL here?

In Laravel, yes. MariaDbGrammar extends MySqlGrammar and inherits $transactions = false, so migrations on MariaDB run without a wrapping transaction.

What does $withinTransaction = false do on PostgreSQL?

It turns the wrapping off for that one migration, so it behaves like MySQL. You need it for CREATE INDEX CONCURRENTLY, which PostgreSQL won't run inside a transaction block. Keep those migrations to a single statement for the same reason.

Can I see which statement failed without a listener?

Yes. The QueryException includes the failing SQL, as in the outputs above. What it can't tell you is which statements before it succeeded. That's the gap the listener fills.

One failing statement per migration

On MySQL and SQLite, a Laravel migration isn't a unit. It's a list of statements that commit one at a time, and the first failure leaves the earlier ones in place. So give each migration at most one statement that can fail. Then the retry after a failure is a data fix and nothing else. Bad indexes are the other MySQL trap that only shows up on production data, and these six Eloquent patterns are the ones I check first.

Top comments (0)