Laravel 內建一套完整的會員系統,除了註冊登入,還有寄送忘記密碼信件、驗證碼信件等等。如果想修改這些寄信服務該怎麼做呢?
創建一個新的 notification:php artisan make:notification ResetPassword
完成後檔案路徑位於 app\\Nofitications\\ResetPassword.php
把原本的寄信功能一字不漏複製過來,原本檔案位置:vendor\\laravel\\framework\\src\\Illuminate\\Auth\\Notifications\\ResetPassword.php
修改裡面的 buildMailMessage()
到 app\\Models\\User.php
,在這裡指定系統使用我們剛寫好的 Notification:
添加:use App\\Notifications\\ResetPassword as ResetPasswordNotification;
添加下列程式碼:
public function sendPasswordResetNotification($token)
{
// my own implementation
$this->notify(new ResetPasswordNotification($token));
}
還想客製化更多信件內容的話,輸入 php artisan vendor:publish --tag=laravel-notifications
resources\\views\\vendor\\notifications\\email.blade.php
想看更多教學點此
Laravel 內建了完整的驗證系統,如果你想修改當中的重設密碼功能,可以這麼做:
系統預設的程式碼位置:vendor\\laravel\\ui\\auth-backend\\SendsPasswordResetEmails.php
在 sendResetLinkEmail()
裡面,有一個 validateEmail($request)
函式,我們要修改它
在 app\\Http\\Controllers\\Auth\\ForgotPasswordController.php
裡面新增以下程式碼:
protected function validateEmail(Request $request)
{
// 驗證使用者輸入是否為空
$request->validate([
'email' => 'required|email',
'g-recaptcha-response' => ['required', new Recaptcha],
]);
// 可以在這裡作其他驗證...
// 如果驗證成功,直接回傳 true or 不回傳皆可
return true;
// 如果驗證失敗,就要讓系統返回前頁,並顯示錯誤訊息
$this->sendIncorrectResponse() // <=== 這個待會實作
}
protected function sendIncorrectResponse()
{
// 返回前頁,並且夾帶 session('status') 訊息
// 以及夾帶 input field 的 輸入錯誤訊息
// (例如這邊就是信箱欄位輸入錯誤)
return back()->with('status', "資訊輸入錯誤。")->withErrors(['email' => "您所輸入的信箱或帳號錯誤,請確認內容後再試一次。"]);
}
如果沒有validateEmail()
的話,就要先在 ForgotPasswordController.php
加入以下內容:
// 必須先 override sendResetLinkEmail()
// sendResetLinkEmail() 會呼叫我們上面寫的 validateEmail()
public function sendResetLinkEmail(Request $request)
{
// 在第一行加入這個
$this->validateEmail($request);
// ... 剩下照抄原版 code
}
如果你還想作其他預設 code 的修改,都直接寫在這個檔案裡即可