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

# Measuring migration duration with the MigrationEnded event

> Get migration durations from Laravel 13's MigrationEnded event and use them for monitoring and tests.

To record how long migrations take, listen for `Illuminate\Database\Events\MigrationEnded`. In Laravel 13.x, the time spent in the `up` or `down` method of a single successful migration is passed as `duration`.

## What the event contains

`MigrationEnded` extends `MigrationEvent` and exposes the migration and the result of the run.

| Property | Type | Contents |
| - | - | - |
| `migration` | `Migration` | The migration instance that ran |
| `method` | `string` | The method that was called, `up` or `down` |
| `name` | `string\|null` | The migration name. Can be `null` depending on how the migration ran |
| `duration` | `float\|null` | How long `up` / `down` took, in milliseconds |

In a normal migration run, `duration` is a `float` rounded to two decimal places. It can be `null`, for example when you create the event yourself, so check the value before your monitoring code uses it.

## Logging the duration

Listen for the event in your application's service provider and pass the data to the log as structured context.

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

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Event::listen(MigrationEnded::class, function (MigrationEnded $event): void {
            Log::info('Database migration finished.', [
                'migration' => $event->name ?? $event->migration::class,
                'class' => $event->migration::class,
                'method' => $event->method,
                'duration_ms' => $event->duration,
            ]);
        });
    }
}
```

Even when `name` is available, also logging `migration::class` makes it easier to identify the migration when it runs through a different path, such as an anonymous class. `duration_ms` is already in milliseconds, so you can send it to logs and metrics without converting it to another unit.

## Event order

Laravel dispatches `MigrationEnded` only when `up` or `down` succeeds.

```mermaid theme={null}
flowchart TD
    A["Dispatch MigrationStarted"] --> B["Start timing"]
    B --> C["Run the migration's up / down"]
    C -->|Success| D["Convert to milliseconds and compute duration"]
    D --> E["Dispatch MigrationEnded"]
    C -->|Exception| F["Dispatch MigrationFailed"]
    F --> G["Rethrow the original exception"]
```

A failed migration doesn't dispatch `MigrationEnded`. Put the code that records the cause of a failure and its exception in a separate `MigrationFailed` listener, as described in [Handling migration failures with the MigrationFailed event](https://kawax.biz/en/advanced/migration-failed-event.md).

## What is measured

The framework starts timing with `microtime(true)` right before it calls the migration method and stops right after `up` or `down` returns. The measurement therefore includes:

* The PHP code inside the migration method
* The database queries that method runs
* Time spent waiting on the database while those queries run

It doesn't include `MigrationStarted` listeners, `MigrationEnded` listeners, or the processing time of the whole migration batch. When schema transactions are used, the timing happens inside the transaction callback, so treat it separately from surrounding work such as starting and committing the transaction.

This value doesn't represent the time of the whole `php artisan migrate` command or of a batch containing several migrations. Use it to compare where time is spent in individual `up` / `down` methods.

## Alerting on migrations over a threshold

Logging a warning only for migrations that exceed a certain time lets you detect slow changes without adding noise to your normal logs.

```php theme={null}
use Illuminate\Database\Events\MigrationEnded;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

Event::listen(MigrationEnded::class, function (MigrationEnded $event): void {
    if ($event->duration === null || $event->duration <= 1000) {
        return;
    }

    Log::warning('Slow database migration detected.', [
        'migration' => $event->name ?? $event->migration::class,
        'method' => $event->method,
        'duration_ms' => $event->duration,
    ]);
});
```

Choose the threshold based on your application's data volume and deployment process. Don't treat a long duration as a failure. Treat it as a "slowness" signal, separate from the exception data in `MigrationFailed`.

## Checking the duration in tests

With `Event::fake` and `Event::assertDispatched`, you can check the shape of `duration` without running the real event listeners.

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

namespace Tests\Feature;

use Illuminate\Database\Events\MigrationEnded;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;

class MigrationDurationTest extends TestCase
{
    public function test_migration_ended_contains_duration(): void
    {
        Event::fake([MigrationEnded::class]);

        $this->artisan('migrate', [
            '--path' => 'tests/Fixtures/migrations',
        ])->assertSuccessful();

        Event::assertDispatched(MigrationEnded::class, function (MigrationEnded $event): bool {
            return $event->method === 'up'
                && is_float($event->duration)
                && $event->duration >= 0;
        });
    }
}
```

To monitor `down` durations as well, run `migrate:rollback` and check for events with `method === 'down'` in the same way. Durations depend on the environment and the state of the database, so test the type and that the value is non-negative rather than a specific number of milliseconds.

## Summary

* `duration` on `MigrationEnded` is the time, in milliseconds, that `up` / `down` of a single successful migration took.
* Send durations to logs and metrics to detect slow migrations.
* Event listeners and the whole batch aren't included, so keep this separate from measuring the performance of the whole command.
* Split monitoring responsibilities: `MigrationFailed` for failures, `MigrationEnded` for slowness in successful runs.

## Primary sources

* [Laravel documentation: Migration events](https://github.com/laravel/docs/blob/13.x/migrations.md#events)
* [Framework 13.x: MigrationEnded](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Events/MigrationEnded.php)
* [Framework 13.x: Event dispatching and timing in Migrator](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Migrations/Migrator.php)
* [Framework 13.x: Migration event tests](https://github.com/laravel/framework/blob/13.x/tests/Integration/Database/MigratorEventsTest.php)


## Related topics

- [Database migrations](https://kawax.biz/en/migrations.md)
- [Handling migration failures with the MigrationFailed event](https://kawax.biz/en/advanced/migration-failed-event.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)
- [Publishing and updating package migrations](https://kawax.biz/en/advanced/package-migrations.md)


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