Laravel: get email recipient from within the mail

2019-07-17 15:18发布

问题:

When using Notifications in Laravel (5.5), you can access the Notifiable (the recipient) from within the toMail() method.

Is there an equivalent way to access the recipient when you are sending a Mailable?

Is there a better solution than just repeating the User instance in the constructor like this?

Mail::to($user)->send(new EventAlert($user));

回答1:

No, there is no way. But you can use Mailable inside a Notification class and use the notification instead of Mailable in a controller or service.

From the docs:

You may return a mailable object from the toMail method

public function toMail($notifiable)
{
    return (new Mailable($this->invoice))->to($this->user->email);
}