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

# 電子郵件驗證（Email Verification）

> 說明實作 Laravel 電子郵件驗證功能的步驟。可學習 model 準備、3 條路由定義、verified middleware、自訂與事件。

## 前言

電子郵件驗證（Email Verification）是確認使用者是否實際擁有所登記電子郵件的機制。Laravel 標準提供寄送確認信與驗證處理，讓你能以最少實作建立安全的認證流程。

<Info>
  使用起始套件時，認證畫面與 email 驗證流程已內建。手動實作時，請依本頁步驟自行定義 model、路由、view。
</Info>

## Model 與資料庫的準備

### 實作 MustVerifyEmail

確認 `App\Models\User` 有實作 `Illuminate\Contracts\Auth\MustVerifyEmail`。

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

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
}
```

加入此介面後，新註冊使用者會自動收到確認信。若非使用起始套件而手動實作註冊，請在註冊成功後觸發 `Registered` 事件。

```php theme={null}
use Illuminate\Auth\Events\Registered;

event(new Registered($user));
```

### 確認 email\_verified\_at 欄位

`users` 資料表需有 `email_verified_at` 欄位。一般預設 `0001_01_01_000000_create_users_table.php` 已包含。

## 路由（3 條路由）

email 驗證需定義 `verification.notice`、`verification.verify`、`verification.send` 3 條路由。

<Steps>
  <Step title="定義驗證通知顯示路由（verification.notice）">
    對未驗證使用者顯示「請確認電子郵件」的畫面。

    ```php theme={null}
    Route::get('/email/verify', function () {
        return view('auth.verify-email');
    })->middleware('auth')->name('verification.notice');
    ```
  </Step>

  <Step title="定義驗證處理路由（verification.verify）">
    當使用者點擊信中連結時，驗證簽章 URL 並完成認證。

    ```php theme={null}
    use Illuminate\Foundation\Auth\EmailVerificationRequest;

    Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
        $request->fulfill();

        return redirect('/home');
    })->middleware(['auth', 'signed'])->name('verification.verify');
    ```
  </Step>

  <Step title="定義重新寄送路由（verification.send）">
    使用者遺失確認信時重新寄送。

    ```php theme={null}
    use Illuminate\Http\Request;

    Route::post('/email/verification-notification', function (Request $request) {
        $request->user()->sendEmailVerificationNotification();

        return back()->with('message', 'Verification link sent!');
    })->middleware(['auth', 'throttle:6,1'])->name('verification.send');
    ```
  </Step>
</Steps>

## 保護路由

要只允許已驗證使用者存取，使用 `verified` middleware。通常與 `auth` 一起用。

```php theme={null}
Route::get('/profile', function () {
    // 只有已驗證使用者可存取
})->middleware(['auth', 'verified']);
```

未驗證使用者存取時，Laravel 會自動導向 `verification.notice`。

## 自訂

要自訂確認信內容，在 `AppServiceProvider` 的 `boot` 方法設定 `VerifyEmail::toMailUsing`。

```php theme={null}
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Notifications\Messages\MailMessage;

public function boot(): void
{
    VerifyEmail::toMailUsing(function (object $notifiable, string $url) {
        return (new MailMessage)
            ->subject('Verify Email Address')
            ->line('Click the button below to verify your email address.')
            ->action('Verify Email Address', $url);
    });
}
```

## 事件

Email 驗證時會觸發 `Illuminate\Auth\Events\Verified` 事件。起始套件會自動處理，手動實作時請視需要加入事件處理。


## Related topics

- [起始套件（Starter Kit）](/zh-TW/starter-kits.md)
- [從 Laravel 8 升級到 9](/zh-TW/blog/upgrade-8-to-9.md)
- [Service Account 驗證 - Google Sheets API for Laravel](/zh-TW/packages/laravel-google-sheets/service-account.md)
- [認證入門](/zh-TW/authentication.md)
- [密碼重設](/zh-TW/passwords.md)
