emaillaravel-5reset-password

Using a Mailable instead of a MailMessage for password reset emails in Laravel 5.5


I'd like my application to use Mailables for all of the emails it sends, so I created my own ResetPasswordEmail class that extends Mailable. Then I created my own ResetPassword notification class that extends the vendor class of the same name and overrode the toMail method as follows:

public function toMail($notifiable)
{
    return (new ResetPasswordEmail())->with('token', $this->token);
}

Then I overrode the sendPasswordResetNotification from the CanResetPassword trait in my User model like this:

public function sendPasswordResetNotification($token)
{
    $this->notify(new ResetPassword($token));
}

Calling my custom ResetPassword notification class.

The problem is that if I use the default method of creating a MailMessage and sending it, it automatically populates the 'to' field with the user's email. But when I use my ResetPasswordEmail mailable class, it doesn't.

Is there a good way to get it to work like that with my custom mailable?


Solution

  • Well in the end I just set the "to" field for my Mailable instance like this:

    public function toMail($notifiable)
    {
        return (new ResetPasswordEmail())->with('token', $this->token)->to($notifiable->email);
    }
    

    Since $notifiable is an instance of the User model in this case, I can get the email like that. I don't know if this is the best way to do it, but it works.