验证邮箱
备注:
由于项目在虚拟机上,所以链接时数据库时,ip地址是虚拟机ip。
上一篇文章已经实现验证邮箱中间件,这次我们实现发送邮件逻辑
1. 创建验证邮件通知类
我们通过 Laravel 内置的通知模块实现邮件发送。
使用 make:notification
命令创建新通知:
生成的通知类在 app/Notifications
目录下,现在我们编辑刚刚生成的通知类:
app/Notifications/EmailVerificationNotification.php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class EmailVerificationNotification extends Notification implements ShouldQueue
{
use Queueable;
// 我们只需要通过邮件通知,因此这里只需要一个 mail 即可
public function via($notifiable)
{
return ['mail'];
}
// 发送邮件时会调用此方法来构建邮件内容,参数就是 App\Models\User 对象
public function toMail($notifiable)
{
return (new MailMessage)
->greeting($notifiable->name.'您好:')
->subject('注册成功,请验证您的邮箱')
->line('请点击下方链接验证您的邮箱')
->action('验证', url('/'));
}
public function toArray($notifiable)
{
return [];
}
}
代码解析:
- 在类的申明里我们加上了
implements ShouldQueue
,ShouldQueue
这个接口本身没有定义任何方法,对于实现了ShouldQueue
的邮件类 Laravel 会用将发邮件的操作放进队列里来实现异步发送; greeting()
方法可以设置邮件的欢迎词;subject()
方法用来设定邮件的标题;line()
方法会在邮件内容里添加一行文字;action()
方法会在邮件内容里添加一个链接按钮。这里就是激活链接,我们暂时把链接设成了主页,接下来我们来实现这个激活链接的逻辑。
2. 激活链接
当发送激活邮件时,我们生成随机字符串,以邮箱为Key,随机字符串保存在缓存中,邮箱和这随机字符串作为激活链接的参数。用户点击激活链接时,我们从缓存中取出对应数据并判断是否一致,就可以确定激活链接是否正确。
首先创建一个控制器 EmailVerificationController
:
$ php artisan make:controller EmailVerificationController
app/Http/Controllers/EmailVerificationController.php
<?php
namespace App\Http\Controllers;
use Exception;
use App\Models\User;
use Illuminate\Support\Facades\Cache;;
use Illuminate\Http\Request;
class EmailVerificationController extends Controller
{
public function verify(Request $request)
{
// 从 url 中获取 `email` 和 `token` 两个参数
$email = $request->