邮件验证(Email Verification)是一种确认用户是否真正拥有其所注册邮箱的机制。Laravel 原生提供了确认邮件的发送与验证处理,让你只需最少的实现就能构建出安全的认证流程。
如果你使用启动套件,认证页面与邮件验证流程都已经内建。手动实现时,请按照本页步骤自行定义模型、路由与视图。
模型与数据库准备
实现 MustVerifyEmail
请确认 App\Models\User 已实现 Illuminate\Contracts\Auth\MustVerifyEmail。
<?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 事件。
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 个路由)
邮件验证需要定义 verification.notice、verification.verify、verification.send 这三个路由。
定义验证通知展示路由(verification.notice)
向未验证的用户返回一个提示「请确认邮件」的页面。Route::get('/email/verify', function () {
return view('auth.verify-email');
})->middleware('auth')->name('verification.notice');
定义验证处理路由(verification.verify)
当用户点击邮件中的链接时,通过校验带签名的 URL 完成认证。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');
定义重新发送路由(verification.send)
当用户找不到确认邮件时用来重新发送。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');
保护路由
如果只允许已认证的用户访问,请使用 verified 中间件。通常与 auth 搭配使用。
Route::get('/profile', function () {
// 仅已验证的用户可访问
})->middleware(['auth', 'verified']);
当未验证用户访问时,Laravel 会自动重定向到 verification.notice。
自定义
要自定义确认邮件的内容,请在 AppServiceProvider 的 boot 方法中设置 VerifyEmail::toMailUsing。
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);
});
}
邮件验证成功时,会触发 Illuminate\Auth\Events\Verified 事件。启动套件已自动处理该事件,如果你是手动实现,请根据需要添加事件处理逻辑。