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

# 使用 MigrationFailed 事件處理遷移失敗

> 使用 Laravel 13 的 MigrationFailed 事件，理解失敗遷移的資訊、交易邊界以及監控與測試的設計。

若要監控遷移失敗，請監聽 `Illuminate\Database\Events\MigrationFailed`。當單一遷移在執行過程中發生例外時，Laravel 會先觸發此事件，然後重新拋出該例外。

這並不是自動重新執行遷移的機制。它是一個用來將失敗的遷移名稱、是 `up` 還是 `down` 失敗，以及原始例外傳遞給日誌與通知的事件。

## 事件包含的資訊

`MigrationFailed` 繼承自 `MigrationEvent`，並公開關於單一遷移的以下值。

| 屬性 | 型別 | 內容 |
| - | - | - |
| `migration` | `Migration` | 正在執行的遷移實例 |
| `method` | `string` | 被呼叫的方法，通常為 `up` 或 `down` |
| `name` | `string\|null` | 遷移名稱。依執行路徑可能為 `null` |
| `exception` | `Throwable` | 造成失敗的例外 |

除了 `name` 之外也記錄 `migration::class`，即使在無法取得檔案名稱的路徑中也能確定目標遷移。使用 `migration->getConnection()` 還可以確認遷移明確指定的連線名稱。

## 註冊監聽器

在應用程式的服務提供者中註冊事件，並將結構化的上下文與原始例外傳遞給日誌。

```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,
            ]);
        });
    }
}
```

讓監聽器專注於記錄失敗，不要在其中修改結構描述或重新執行遷移。由於原始例外會在事件之後被重新拋出，`php artisan migrate` 與 `php artisan migrate:rollback` 仍會以失敗結束。

## 觸發順序

對於一般的單一遷移，`Migrator` 依以下順序觸發事件。

```mermaid theme={null}
flowchart TD
    A["MigrationsStarted<br>批次開始"] --> B["MigrationStarted<br>單一遷移開始"]
    B --> C{"up / down 成功?"}
    C -->|成功| D["MigrationEnded<br>單一遷移完成"]
    D --> E["下一個遷移"]
    E --> F["MigrationsEnded<br>批次完成"]
    C -->|例外| G["MigrationFailed<br>保存例外"]
    G --> H["重新拋出原始例外"]
```

`MigrationEnded` 只在執行成功時觸發。如果遷移的處理，或執行過程中觸發的事件的監聽器拋出例外，就會進入 `runMigration` 的例外處理，並觸發 `MigrationFailed`。

此外，若在批次中途重新拋出例外，剩餘的遷移將不會執行。因此，失敗的批次不一定會觸發 `MigrationsEnded`。不要只用同一個事件同時處理批次完成與失敗。

## 與交易的關係

當資料庫的 Schema Grammar 支援結構描述交易，且遷移的 `withinTransaction` 為啟用狀態時，Laravel 會以交易包住執行過程。

```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');
        });
    }
};
```

若在此路徑中處理失敗，`MigrationFailed` 會在交易回滾之後觸發。但在以下情況下，資料庫不一定能回滾所有操作：

* 所使用的資料庫或 Schema Grammar 不支援結構描述交易
* 遷移中指定了 `public $withinTransaction = false`
* 資料庫不將 DDL 視為交易處理

因此，不要僅憑收到此事件就判斷結構描述已回到原始狀態。在發生失敗的環境中，請先確認實際的結構描述與 `migrations` 資料表的狀態，再進行復原。

## 區分 `up` 與 `down` 的失敗

回滾失敗也透過同一事件通知。檢查 `method`，即可在套用與撤銷時區分通知對象與維運流程。

```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,
    ]);
});
```

當 `down` 失敗時，例外發生在目標遷移從 `migrations` 資料表刪除之前。`Migrator` 只在 `down` 正常完成後才執行刪除，因此失敗後請同時確認實際的結構描述與記錄。

## 監控與通知的邊界

`MigrationFailed` 在執行部署或手動 Artisan 指令的處理程序內同步處理。將通知放入佇列，就能在不掩蓋遷移指令本身失敗的前提下，把通知的傳送分離到後續處理。

但應避免在監聽器中重新執行失敗的遷移。在同一指令尚未結束時重新執行，會使鎖定、部分套用的 DDL 以及部署順序等問題變得複雜。需要重新執行時，請先修正原因並確認狀態，再作為維運流程執行。

## 在測試中確認事件

準備一個會失敗的測試用遷移，確認 Artisan 指令失敗，且事件持有造成失敗的例外。不要把測試用遷移放在正式環境的掃描範圍內。

```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` 會記錄事件，因此可以與應用程式實際的通知處理分開測試。是否發生回滾、DDL 是否會部分殘留，請使用所用資料庫與 Schema Grammar 撰寫另外的整合測試來確認。

## 總結

* 單一遷移失敗時，`MigrationFailed` 會傳遞 `migration`、`method`、`name` 與 `exception`。
* `MigrationEnded` 只在成功時觸發，`MigrationsEnded` 只在批次完整執行完畢時觸發。
* 交易與 DDL 的行為因資料庫而異，因此不要把該事件當作回滾的保證。
* 將監聽器限定於監控與通知，重新執行與復原應在確認原因與結構描述後作為維運流程進行。

## 參考的第一手資料

* [Laravel 官方文件：遷移事件](https://github.com/laravel/docs/blob/13.x/migrations.md#events)
* [Laravel 官方文件：事件監聽器](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: Migrator 的事件觸發](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Migrations/Migrator.php#L435-L460)
* [Framework 13.x: Migration 基礎類別](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Migrations/Migration.php)


## Related topics

- [進階主題](https://kawax.biz/zh-TW/advanced/index.md)
- [資料庫遷移（Migrations）](https://kawax.biz/zh-TW/migrations.md)
- [事件與監聽器](https://kawax.biz/zh-TW/events.md)
- [事件](https://kawax.biz/zh-TW/packages/laravel-copilot-sdk/events.md)
- [開始使用 - GitHub Copilot SDK for Laravel](https://kawax.biz/zh-TW/packages/laravel-copilot-sdk/getting-started.md)


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