Laravel Steps

Laravel Event

2018-11-02  本文已影响0人  AnnaJIAN

写一个注册成功之后,自动触发验证邮件的例子

Provider 里面让注册成功这个event 和 监听他的lisener类绑定

EventServiceProvider.php
use Illuminate\Auth\Events\Registered;
use App\Listeners\RegisteredListener;
...
protected $listen = [
    Registered::class => [
        RegisteredListener::class,
    ],
];

Listener里面写入需要触发的函数

RegisteredListener.php
use Illuminate\Auth\Events\Registered;
use App\Notifications\EmailVerificationNotification;
...
public function handle(Registered $event)
{
    // Get the registed user.
    $user = $event->user;
    $user->notify(new EmailVerificationNotification());
}

需要触发的发邮件函数具体内容

class EmailVerificationNotification extends Notification implements ShouldQueue
{
...
public function toMail($notifiable)
{
    $token = Str::random(16);
    Cache::set('email_verification_' . $notifiable->email, $token, 30);
    $url = route('email_verification.verify', ['email' => $notifiable->email, 'token' => $token]);
    return (new MailMessage)
                ->greeting($notifiable->name . 'Hello:')
                ->subject('注册成功,请验证你的邮箱')
                ->line('请点击下方链接验证您的邮箱')
                ->action('验证', $url);
}

完成了。
一般发邮件这种事需要放到队列里面去处理, implements ShouldQueue将会自动把发邮件放入队列。具体如何工作,研究后再更。

Tips: notify 的用法参照:
https://laravel-china.org/docs/laravel/5.5/notifications

上一篇 下一篇

猜你喜欢

热点阅读