Laravel — 在瀏覽器預覽Notifications Email(How to preview your emails notifications in browser — Laravel)

hosomikai
3 min readJun 11, 2020

--

Photo by Krsto Jevtic on Unsplash

通知信件對任何一個網站服務來說都是一個很必須很常見的基本功能。
在開發階段的時候不論是修改樣式或是做其他調整,我們都會需要查看傳送出去的結果是否如預期。
但是如果每次都要真實發送出去才能查看的話是否太麻煩了呢?

本篇文章跟你分享一個小技巧,讓你可以在瀏覽器上預覽你所寄出的mail在收件者的信箱是長怎樣。

Laravel 5.6

Route::get('preview-email', function () {
$order = App\Models\Order::first();
$message = (new App\Notifications\OrderPaid($order))
->toMail($order->user);
$markdown = new Illuminate\Mail\Markdown(
view(),
config('mail.markdown'));
return $markdown->render($message->markdown, $message->data());});

我們在route檔案裡 routes/web.php 為我們的預覽mail加入一個 GET 方法的Route,準備好你的Notifications 的物件($message)。
然後我們需要透過 Illuminate\Mail\Markdown 的物件去把我們的 $message render出來。
然後在你的瀏覽器裡瀏覽 http://yourhostname/preview-email ,我們就可以預覽我們寫好的 email notification了!

Laravel > 5.8

Laravel 5.8之後的版本, MailMessage 實作了Illuminate\Contracts\Support\Renderable 的介面(Interface),當一個 MailMessage 被 return 的時候,他會自動幫你render出 MailMessage 的mail模板,算是Laravel提供的一個小魔術。

Route::get('preview-email', function () {
$order = App\Models\Order::first();
return (new App\Notifications\OrderPaid($order))
->toMail($order->user);
});

所以只要直接return你的 MailMessage 就可以預覽你的mail notification!
當然你也可以直接調用他的 render 方法:

Route::get('preview-email', function () {
$order = App\Models\Order::first();
$message = (new App\Notifications\OrderPaid($order))
->toMail($order->user);
return $message->render();});

以上就是今天跟大家分享的如何在瀏覽器上預覽mail notification的小技巧,希望對大家有幫助!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response