Laravel 7 Custom Password Rest Email Template

Categories: Development, General

The Laravel documentation mentions that you can customize the Password Rest Template, but doesn’t explain how you would actually do it. That said, I will assume that you already have auth and have published your auth views. That is covered very well in the documentation.

As stated in the documentation you will need to over overwrite the sendPasswordResetNotification method in the User model.

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

Now for the fun part, Laravel uses Notifications in order to send the Password Reset emails. So we will have to make a new notification called ResetPasswordNotification.

php artisan make:notification ResetPasswordNotification

Inside your ResetPasswordNotification class and in the toMail method we need two things, a reset URL and the Email it’s self.

The reset URL is built up using a Token and the users email address.

The token is automatically passed to the notification for us in the User model but in order to make it available to the toMail method. We will have to add it to the constructor.

    private $token;
    
    public function __construct($data)
    {
        $this->token = $data;
    }

And don’t forget to declare your property as private.

The user’s email is part of the $notifiable parameter, so we can call $notifiable->getEmailForPasswordReset()

$url = url(config('app.url') . route('password.reset', [
        'token' => $this->token,
        'email' => $notifiable->getEmailForPasswordReset(),
    ], false));

Next up, we have to build the Email its self, buy generating a new MailMessage.

return (new MailMessage)->view('emails.user.reset', ['url' => $url]);

Depending on your email template, I personally chose to use Blade and regular HTML, Simply display the URL in your template {{ $url }}.

The completed toMail method now looks like this.

public function toMail($notifiable)
{
    $url = url(config('app.url') . route('password.reset', [
            'token' => $this->token,
            'email' => $notifiable->getEmailForPasswordReset(),
        ], false));

    return (new MailMessage)->view('emails.user.reset', ['url' => $url]);
}

I’m sure you can see that this was actually a simple step to ensure the consistency of your app, and I hope this helped you out. I know when I was trying to figure this out I was not 100% familiar with the MailMessage or Notifications.


Adam Patterson

Adam Patterson

User Interface Designer & Developer with a background in UX. I have spent 5 years as a professionally certified bicycle mechanic and ride year-round.

I am a husband and father of two, I enjoy photography, music, movies, coffee, and good food.

You can find me on Twitter, Instagram, and YouTube!