9

With Laravel, according to the documentation, I can return a Mailable via a controller to display it in the browser. It helps to preview mails.

Is there a way to preview Mail Notifications in browser?

I tried:

return (new MyNotification())->toMail($some_user);

But it does not work:

The Response content must be a string or object implementing __toString(), "object" given.

rap-2-h
  • 30,204
  • 37
  • 167
  • 263

5 Answers5

12

In your controller's function :

 $message = (new \App\Notifications\MyNotification())->toMail('example@gmail.com');    
 $markdown = new \Illuminate\Mail\Markdown(view(), config('mail.markdown'));

return $markdown->render('vendor.notifications.email', $message->data());

Just change the name of the notification class (and also pass arguments if necessary) and hit the url in your browser to see the preview.

Slava V
  • 16,686
  • 14
  • 60
  • 63
black_belt
  • 6,601
  • 36
  • 121
  • 185
7

In Laravel 5.8 you can now preview it just like you would a Mailable.

Route::get('mail-preview', function () {
    return (new MyNotification())->toMail($some_user);
});

More details here: https://sampo.co.uk/blog/previewing-mail-notifications-in-laravel-just-got-easier

BenSampo
  • 559
  • 5
  • 8
6

You can't render Notification. You can render Mailable that you use in toMail(). For example if that Mailable is called SomeMailable:

public function toMail($user)
{
    return (new SomeMailable($user))->to($user->email);
}

Then you can render the Mailable with:

return new SomeMailable($some_user);
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

For me, with the particular notification that I wanted to preview toMail() method required a Notifiable instance rather than just an email address, so the following code was what worked for me:

    $notification = new \Illuminate\Auth\Notifications\VerifyEmail();

    $user = \App\User::where('email', 'example@gmail.com')->first(); // Model with Notifiable trait

    $message = $notification->toMail($user);

    $markdown = new \Illuminate\Mail\Markdown(view(), config('mail.markdown'));

    return $markdown->render('vendor.notifications.email', $message->toArray());
Matt Sims
  • 553
  • 1
  • 5
  • 14
0

Try this (Test pass after Laravel 5.6)

$message = (new \App\Notifications\YourNotification()->toMail($notifiable);

return app()->make(\Illuminate\Mail\Markdown::class)->render($message->markdown, $message->data());
Daniel Sun
  • 50
  • 5