Laravel reset password email 重置 重設 密碼
Laravel PHP

Laravel reset password email 重設密碼

商業,創業,業務,職涯,美食,葡萄酒,閱讀,網路科技。

從 Larry 創業以及商業的經驗,希望以白話的口吻,介紹給大家這個商業的世界。

FB粉專會頻繁地更新 Larry 對於商業、社會、人生的觀察與心得,歡迎大家追蹤互動~

圖片來源 https://github.com/laravel/laravel

https://laravel.com/docs/5.5/passwords
因為每次要做 Laravel 重設密碼的 email 都要去改 Laravel 框架內部的 code, 不是很優,決定花點時間研究什麼是比較正確的做法。

******* 以下是以 Laravel 5.5 而言 *******

app\User 繼承 Illuminate\Foundation\Auth\User, 它實作 Illuminate\Contracts\Auth\CanResetPassword

CanResetPassword 是一個 interface class, 有一個 function  sendPasswordResetNotification($token)
https://github.com/laravel/framework/blob/5.5/src/Illuminate/Contracts/Auth/CanResetPassword.php

另 Illuminate\Foundation\Auth\User use trait Illuminate\Auth\Passwords\CanResetPassword
https://github.com/laravel/framework/blob/5.5/src/Illuminate/Auth/Passwords/CanResetPassword.php

Illuminate\Auth\Passwords\CanResetPassword 已經實作好 (我們不用動)

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

我們就照官方的命名 ResetPasswordNotification, 新增一個 notification class

php artisan make:notification ResetPasswordNotification

生成的 ResetPasswordNotification 很貼心的已經有 function toMail($notifiable), 把你希望的 mail 內容填在裡面。記得之前傳了一個 token 進來,記得要在 ResetPasswordNotification constructor 去接這 token (dependency injection pattern)

一些通知信的內容寫法 (function toMail 的內容),可以參考這份文件
https://laravel.com/docs/5.5/notifications#mail-notifications

上方連結提到你也可以用 view 的方式來撰寫信件內容 (larry 個人認為這是較好的方式)

return (new MailMessage)->view(
        'emails.name', ['invoice' => $this->invoice]);

上方連結提到,信件的標題預設是「the class name of the notification formatted to “title case”」所以如果 class name 是 ResetPasswordNotification, 預設的信件標題就是 “Reset Password Notification”. 信件標題當然要改,設定如下:

return (new MailMessage)
                ->subject('Notification Subject')
                ->line('...');

以上大概就是一個比較好的 reset password email 的寫法 ~

商業,創業,業務,職涯,美食,葡萄酒,閱讀,網路科技。

從 Larry 創業以及商業的經驗,希望以白話的口吻,介紹給大家這個商業的世界。

FB粉專會頻繁地更新 Larry 對於商業、社會、人生的觀察與心得,歡迎大家追蹤互動~