LoginSignup
7
2

More than 1 year has passed since last update.

Laravelのパスワード再設定のメールをカスタマイズする

Last updated at Posted at 2021-09-29

これはなに

公式ドキュメントには手順として簡単なものしかなかったため
Laravelのパスワードリセットのカスタマイズについてメモします。

ResetPasswordNotification.phpでメールアドレスを渡しつつ、
markdownでメールを送信した手順を書き残しておきます。

前提

  • Laravel Breezeをインストール済みなど、各種認証APIが実装されているものとします。
  • メール送信の設定は済んでいるものとします。

動作確認環境

PHP8.0
Laravel8

Modelの変更

User.phpでsendPasswordResetNotificationメソッドを追加してオーバーライドします。

User.php
    public function sendPasswordResetNotification($token): void
    {
        $this->notify(new ResetPasswordNotification($token));
    }

Notificationとテンプレートの設定

コマンドでNotificationを作成します。

$ php artisan make:notification ResetPasswordNotification

$tokenを受け取れるようにします。

app/Notifications/ResetPasswordNotification.php
+    private string $token;

-    public function __construct()
+    public function __construct(string $token)
    {
+        $this->token = $token;
    }

$notifiable->emailでメールアドレスを取得できます。
クエリパラメーターにのせるとフォームの初期値にできるので渡しておきます。

app/Notifications/ResetPasswordNotification.php
    public function toMail(mixed $notifiable): MailMessage
    {
        $url = urldecode(url('reset-password', $this->token . '?email=' . $notifiable->email));
        return (new MailMessage())
            ->subject('【' . config('app.name') . '】パスワード再設定')
            ->markdown('mail.passwordreset', ['reset_url' => $url]);
    }

続いてmarkdownのテンプレートを作成します。

views/passwordreset.blade.php
@component('mail::message')
ボタンを押してパスワードリセットの手続きを行ってください

@component('mail::button', ['url' => $reset_url])
パスワードリセット
@endcomponent

----
もしこのメールに心当たりがない場合は破棄してください

@endcomponent

画面からテンプレートを確認する

いちいちメールを送信せずともブラウザからテンプレートを確認できるようにします。

routes/auth.php
if (app()->isLocal()) {
    Route::get('/forgot-password-email', function () {
        $user = new User([
            'email' => 'user@example.com',
        ]);
        return (new \App\Notifications\ResetPasswordNotification('test_token'))->toMail($user);
    });
}

ブラウザから該当パスへアクセスします。問題なく表示できました。

qiita_laravel_reset_pass.png

テンプレートにLaravelロゴが表示されている場合は、.envのAPP_NAMEを 'Laravel' 以外に設定すると置き換えできます。

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2