如何排队Laravel 5.7"电子邮件验证"电子邮件发送

Fra*_*ois 3 queue email-verification laravel laravel-5.7

Laravel 5.7包含"电子邮件验证"功能,但不是异步电子邮件发送(在用户注册或重新发送链接页面期间)并不理想.

有没有办法通过队列发送电子邮件验证电子邮件而不重写Laravel 5.7中的整个电子邮件验证?

pat*_*cus 14

没有内置的方式,但是您可以通过扩展和覆盖来轻松实现。

首先,创建一个扩展内置通知的新通知,并实现ShouldQueue合同(以启用排队)。下列类假定您在处创建通知app/Notifications/VerifyEmailQueued.php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Auth\Notifications\VerifyEmail;

class VerifyEmailQueued extends VerifyEmail implements ShouldQueue
{
    use Queueable;

    // Nothing else needs to go here unless you want to customize
    // the notification in any way.
}
Run Code Online (Sandbox Code Playgroud)

现在,您需要告诉框架使用自定义通知而不是默认通知。您可以通过重写这样做sendEmailVerificationNotification()对你User的模型。这只是更改了发出的通知。

public function sendEmailVerificationNotification()
{
    $this->notify(new \App\Notifications\VerifyEmailQueued);
}
Run Code Online (Sandbox Code Playgroud)

  • 像一个charn一样工作! (2认同)
  • 这比公认的答案简单得多,而且有效 (2认同)

Yve*_*ndo 8

是! 这是可能的.要做到这一点,你将不得不改写sendEmailVerificationNotification你的App\User.该方法由Illuminate\Auth\MustVerfiyEmail特征提供.该方法通过在Notification类中定义发送Email来sendEmailVerificationNotification通知创建userIlluminate\Auth\Notifications\VerifyEmail.

// This is the code define in the sendEmailVerificationNotification
public function sendEmailVerificationNotification()
{
    $this->notify(new Notifications\VerifyEmail);
}
Run Code Online (Sandbox Code Playgroud)

您可以将此方法更改为不直接通知用户.您必须定义一个Job您将在sendEmailVerificationNotification方法中调度的内容,而不是通知创建的用户.

Job您将在其中创建的类中,您handle可以将电子邮件发送给该方法user但您必须$user通过将其作为参数传递给dispatch方法来提供可以执行的作业,如下所示

public function sendEmailVerificationNotification()
{
    VerifyEmail::dispatch($this);
}
Run Code Online (Sandbox Code Playgroud)

$this该方法代表了创造userApp\Jobs\VerififyEmail您将创建工作将得到所有的参数传递给dispatch__construct

VerifyEmail遗嘱的代码看起来像这样

namespace App\Jobs;

use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Auth\Notifications\VerifyEmail;

class VerifyEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function handle()
    {
        // Here the email verification will be sent to the user
        $this->user->notify(new VerifyEmail);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以通过将 Laravel 的类别名为另一个名称来使用相同的类名,例如:`use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailNotification;` 和 `handle` 方法中的 `$this->user->notify(new VerifyEmailNotification) ;`。在我看来,这更清晰一些,但这只是吹毛求疵。 (2认同)