> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Handling migration failures with the MigrationFailed event

> Use Laravel 13's MigrationFailed event to understand the data a failed migration exposes, transaction boundaries, and how to design monitoring and tests.

To monitor migration failures, listen for `Illuminate\Database\Events\MigrationFailed`. When an exception occurs while a single migration runs, Laravel dispatches this event and then rethrows the exception.

This is not a mechanism that reruns migrations automatically. The event exists to pass the name of the failed migration, whether `up` or `down` failed, and the original exception on to logs and notifications.

## Data the event carries

`MigrationFailed` extends `MigrationEvent` and exposes the following values for a single migration.

| Property | Type | Description |
| - | - | - |
| `migration` | `Migration` | The migration instance being run |
| `method` | `string` | The method that was called, usually `up` or `down` |
| `name` | `string\|null` | The migration name. Can be `null` depending on the execution path |
| `exception` | `Throwable` | The exception that caused the failure |

If you record `migration::class` in addition to `name`, you can identify the migration even on paths where the file name isn't available. With `migration->getConnection()`, you can also check the connection name the migration specified explicitly.

## Registering a listener

Register the event in your application's service provider and pass structured context and the original exception to the log.

```php theme={null}
<?php

namespace App\Providers;

use Illuminate\Database\Events\MigrationFailed;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Event::listen(MigrationFailed::class, function (MigrationFailed $event): void {
            Log::error('Database migration failed.', [
                'migration' => $event->name,
                'class' => $event->migration::class,
                'method' => $event->method,
                'connection' => $event->migration->getConnection(),
                'exception' => $event->exception,
            ]);
        });
    }
}
```

Keep the listener focused on recording the failure, and don't change the schema or rerun migrations from it. Because the original exception is rethrown after the event, `php artisan migrate` and `php artisan migrate:rollback` still exit with a failure.

## Dispatch order

For a normal single migration, `Migrator` dispatches events in the following order.

```mermaid theme={null}
flowchart TD
    A["MigrationsStarted<br>Batch starts"] --> B["MigrationStarted<br>Single migration starts"]
    B --> C{"up / down succeeded?"}
    C -->|Success| D["MigrationEnded<br>Single migration finished"]
    D --> E["Next migration"]
    E --> F["MigrationsEnded<br>Batch finished"]
    C -->|Exception| G["MigrationFailed<br>Holds the exception"]
    G --> H["Rethrow the original exception"]
```

`MigrationEnded` is dispatched only when the run succeeds. If the migration's work, or a listener for an event dispatched during the run, throws an exception, execution enters the exception handling in `runMigration` and `MigrationFailed` is dispatched.

When the exception is rethrown in the middle of a batch, the remaining migrations don't run. As a result, `MigrationsEnded` isn't necessarily dispatched for a failed batch. Don't rely on a single event to handle both batch completion and failure.

## Relationship to transactions

When the database's Schema Grammar supports schema transactions and the migration's `withinTransaction` is enabled, Laravel wraps the run in a transaction.

```php theme={null}
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('orders', function (Blueprint $table): void {
            $table->string('status');
        });
    }
};
```

If the work fails on this path, `MigrationFailed` is dispatched after the transaction rolls back. However, the database can't always roll back every operation, for example when:

* The database or Schema Grammar you use doesn't support schema transactions
* The migration sets `public $withinTransaction = false`
* The database doesn't treat DDL as transactional

So don't conclude that the schema is back to its original state just because you received this event. In the failed environment, check the actual schema and the state of the `migrations` table before recovering.

## Telling `up` and `down` failures apart

Rollback failures are reported through the same event. Check `method` to route notifications and runbooks differently for applying and reverting.

```php theme={null}
Event::listen(MigrationFailed::class, function (MigrationFailed $event): void {
    $operation = $event->method === 'down' ? 'rollback' : 'migrate';

    Log::critical('Migration operation failed.', [
        'operation' => $operation,
        'migration' => $event->name ?? $event->migration::class,
        'exception' => $event->exception,
    ]);
});
```

When `down` fails, the exception occurs before the migration is removed from the `migrations` table. `Migrator` performs the removal only after `down` completes successfully, so after a failure, check both the actual schema and the record.

## Boundaries of monitoring and notifications

`MigrationFailed` is handled synchronously in the process that ran the deployment or the manual Artisan command. If you queue the notification, you can move its delivery to later processing without hiding the failure of the migration command itself.

However, avoid rerunning the failed migration from the listener. Rerunning it before the same command has finished complicates locks, partially applied DDL, and deployment ordering. When a rerun is necessary, fix the cause, check the state, and then run it as an operational procedure.

## Verifying the event in tests

Prepare a test migration that fails, and verify that the Artisan command fails and that the event carries the causing exception. Don't place test migrations where production migration discovery can find them.

```php theme={null}
<?php

namespace Tests\Feature;

use Illuminate\Database\Events\MigrationFailed;
use Illuminate\Support\Facades\Event;
use RuntimeException;
use Tests\TestCase;

class MigrationFailureTest extends TestCase
{
    public function test_failed_migration_dispatches_event(): void
    {
        Event::fake([MigrationFailed::class]);

        $this->artisan('migrate', [
            '--path' => 'tests/Fixtures/migrations/2026_01_01_000000_fail.php',
        ])->assertFailed();

        Event::assertDispatched(MigrationFailed::class, function (MigrationFailed $event): bool {
            return $event->method === 'up'
                && $event->exception instanceof RuntimeException;
        });
    }
}
```

`Event::fake` records events, so you can test separately from your application's actual notification handling. Verify whether a rollback happens, and that no DDL is left partially applied, in separate integration tests that use your database and Schema Grammar.

## Summary

* `MigrationFailed` passes `migration`, `method`, `name`, and `exception` when a single migration fails.
* `MigrationEnded` is dispatched only on success, and `MigrationsEnded` only when the batch runs to completion.
* Transaction and DDL behavior differs by database, so don't treat the event as a rollback guarantee.
* Limit listeners to monitoring and notifications, and perform reruns and recovery as an operational procedure after checking the cause and the schema.

## Primary sources

* [Laravel documentation: Migration events](https://github.com/laravel/docs/blob/13.x/migrations.md#events)
* [Laravel documentation: Event listeners](https://github.com/laravel/docs/blob/13.x/events.md#registering-events-and-listeners)
* [Framework 13.x: MigrationFailed](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Events/MigrationFailed.php)
* [Framework 13.x: MigrationEvent](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Events/MigrationEvent.php)
* [Framework 13.x: Event dispatching in Migrator](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Migrations/Migrator.php#L435-L460)
* [Framework 13.x: Migration base class](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Migrations/Migration.php)


## Related topics

- [Database migrations](https://kawax.biz/en/migrations.md)
- [Advanced Topics](https://kawax.biz/en/advanced/index.md)
- [Migration Guide: Old Structure to Slim Application Skeleton](https://kawax.biz/en/advanced/app-structure-migration.md)
- [Exceptions and error handling](https://kawax.biz/en/packages/laravel-copilot-sdk/exceptions.md)
- [Streaming events](https://kawax.biz/en/packages/laravel-copilot-sdk/streaming-events.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.