Laravel邮箱验证的一般步骤

这部分内容主要是参考Laravel文档的内容进行的笔记记录,具体效果还没有使用过,如果之后有使用到,再进行一下记录。

使用MustVerifyEmail接口

首先要在用户Model中引入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;

    // ...
}

手动分发注册事件

在EventServiceProvider中的Registered事件中已经附加了SendEmailVerificationNotification监听器,在用户注册成功后需要手动分发Illuminate\Auth\Events\Registered事件。

use Illuminate\Auth\Events\Registered;

event(new Registered($user));

数据库

需要在user包含email_verified_at字段,来记录邮箱通过验证的时间。

路由

需要三个路由,一个向用户发送要求验证邮件的通知,一个处理用户点击验证链接的请求,一个处理没接到邮件点击重发邮件的情况。

Route::get('/email/verify', function () {
    return view('auth.verify-email');
})->middleware('auth')->name('verification.notice');

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');
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中间件可以阻止未通过邮箱验证的用户进行访问,未通过验证的用户会被自动重定向到verification.notice命名路由。

Route::get('/profile', function () {
    // 只有经过验证的用户才能进入...
})->middleware('verified');

自定义邮箱和事件

use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Notifications\Messages\MailMessage;

/**
 * 注册任何身份验证/授权服务
 *
 * @return void
 */
public function boot()
{
    // ...

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

自定义发送邮件的格式:把闭包函数发送给toMailUsing方法,闭包将接收可通知模型的实例,以及用户必须访问的包含签名的验证 URL。闭包将返回一个 Illuminate\Notifications\Messages\MailMessage实例。通常您应该在应用中的App\Providers\AuthServiceProvider类的boot方法中调用toMailUsing方法。

事件想要接收并且进行手动处理的话,应该在EventServiceProvider中注册监听者。

/**
 * 应用程序的事件监听器
 *
 * @var array
 */
protected $listen = [
    'Illuminate\Auth\Events\Verified' => [
        'App\Listeners\LogVerifiedUser',
    ],
];