Laravel
裏我們可以使用php artisan make:auth
來生成一套默認的登陸註冊重置郵箱的Authentication System
,但是如何修改系統發送給用戶的重置密碼郵件的樣式和內容呢?
雖然默認的郵件樣式很美觀,但是不免全部是英文,我們至少可以添加進一些中文提示,方便用戶查看。
首先我們需要明確的是:
- Laravel 默認的 Notification Class是ResetPassword,位於
Illumintate/Auth/Notifications
中。- 我們不應該直接修改位於ResetPassword裏的代碼,因爲如果更新package可能導致覆蓋。
我們先來看一下ResetPassword
:
<?php
namespace Illuminate\Auth\Notifications;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class ResetPassword extends Notification
{
public $token;
public function __construct($token)
{
$this->token = $token;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->line('You are receiving this email because we received a password reset request for your account')
->action('Reset Password', url(config('app.url').route('password.reset', $this->token, false)))
->line('If you did not request a password reset, no further action is required.');
}
}
可以看到,ResetPassword
拓展了Notification
這個類,所以我們需要做的就是新建一個Notification
類,來完成我們自定義郵件內容的修改:
$ php artisan make:notification ResetPasswordNotification
輸入以上artisan
命令,我們會發現在App\Notifications
文件夾下多出了一個名爲ResetPasswordNotification.php
的文件,打開它,我們可以看到其內容跟ResetPassword
很相似。我們只需要修改關鍵的代碼即可:
<?php
namespace Illuminate\Auth\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class ResetPasswordNotification extends Notification
{
use Queueable;
public $token;
public function __construct($token)
{
$this->token = $token;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->line('這裏可以放我們需要添加的內容')
->line('You are receiving this email because we received a password reset request for your account')
->action('Reset Password', url(config('app.url').route('password.reset', $this->token, false)))
->line('這裏可以放我們需要添加的內容')
->line('If you did not request a password reset, no further action is required.');
}
}
可以看到,我們可以以line作爲單位來添加我們需要的信息。
那麼信息內容搞定了,怎麼樣修改郵件樣式呢?首先我們需要能夠修改信息的Blade
模板:
$ php artisan vendor:publish --tag=laravel-notifications
以上命令把包裹裏的模板發佈到resources/views/vendor/notifications
文件夾中,這樣我們只需要修改resources/views/vendor/notifications/email.blade.php
就可以了。
最後一步,我們在User
模型裏添加:
/**
* Send the password reset notification.
*
* @param string $token
* @return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPasswordNotification($token));
}
這樣,我們就可以使用ResetPasswordNotification
來進行郵件的發送了。
模板的修改很簡單,這裏就不贅述了,完成後,我們可以看到新的郵件內容: