0

我想允许管理员用户添加新用户,这些用户应该会收到一封通知电子邮件,但我不想使用 $user->sendEmailVerificationNotification();,因为我想自定义我发送给他们的消息,所以有时我可以使用默认值 sendEmailVerificationNotification();,但有时我想使用customSendEmailVerificationNotification()

这样做的正确方法是什么?

4

1 回答 1

2

如果您只需要自定义消息,根据文档,您可以将闭包传递给通知toMailUsing提供的方法。Illuminate\Auth\Notifications\VerifyEmail

// AuthServiceProvider

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

/**
 * Register any authentication / authorization services.
 *
 * @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);
    });
}

如果您还想更改通知电子邮件的结构,您可以通过运行以下命令发布通知视图:

php artisan vendor:publish --tag=laravel-notifications

在此之后,您可以继续对视图进行任何更改。请注意,这将适用于通过应用程序发送的所有通知,而不仅仅是验证电子邮件。

编辑:

sendEmailVerificationNotification()如果您想有条件地发送通知,您还可以覆盖:

use Illuminate\Auth\Notifications\VerifyEmail;
use App\Notifications\CustomVerifyEmail;

class User extends Authenticatable implements MustVerifyEmail
{
    public function sendEmailVerificationNotification()
    {
        $condition ? $this->notify(new CustomVerifyEmail) : $this->notify(new VerifyEmail);
    }
} 
于 2022-01-27T13:49:24.463 回答