3
3

More than 5 years have passed since last update.

Laravel 5.7 パスワードリセットの日本語化

Last updated at Posted at 2019-02-27

こちらはブログでも掲載しています。

前回、メールアドレスの確認と日本語化したのですが、パスワードリセットでも英文のメールが送られていたので、こちらも日本語化をしたいと思います。

Laravel 5.7 メールアドレスの確認を日本語化も含めて実装する

ユーザー認証は以下のコマンドで実装されているものとします。

php artisan make:auth

ビューの日本語化

まずは、パスワードリセットの画面を日本語化します。

./resources/views/auth
├── passwords
│   ├── email.blade.php
│   └── reset.blade.php
@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('message.password_reset.title') }}</div>

                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif

                    <form method="POST" action="{{ route('password.email') }}">
                        @csrf

                        <div class="form-group row">
                            <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('message.user.field.email') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>

                                @if ($errors->has('email'))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('message.button.send') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

翻訳ファイルも変更します。(./resources/lang/ja/message.php)

<?php
return [
    // ボタン
    "button" => [
        "send" => ' 送信 ',
    ],
    // ユーザ情報
    "user" => [
        "field" => [
            "email" => "メールアドレス",
        ]
    ],
    // パスワードリセット
    "password_reset" => [
        'title' => 'パスワードリセット'
    ],
];

送信メールの日本語化

まずは、パスワードリセットをしたときにどこでメールを送っているのかを確認します。

UserモデルがAuthenticatable(Illuminate\Foundation\Auth\User)を継承しています。

その中で、CanResetPasswordというtraitを呼び出しています。

class User extends Model implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail;
}

CanResetPasswordの中身を見ると、sendPasswordResetNotificationでメールを送っているので、こちらをカスタマイズしていきます。

trait CanResetPassword
{
    /**
     * Get the e-mail address where password reset links are sent.
     *
     * @return string
     */
    public function getEmailForPasswordReset()
    {
        return $this->email;
    }

    /**
     * Send the password reset notification.
     *
     * @param  string  $token
     * @return void
     */
    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetPasswordNotification($token));
    }
}

カスタムのNotificationを作成する

artisanを利用して、カスタムのNotificationを作成します。

php artisan make:notification RestPasswordCustom

./app/Notifications/にファイルが作成されるので、もともとパスワードリセットで使用されているRestPasswordNotification(Illuminate\Auth\Notifications\ResetPassword)を参考に編集をいたします。

変更箇所はtoMailの中で、英文をセットしている箇所を日本語に置き換えるだけです。

namespace App\Notifications;

use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Lang;

class RestPasswordCustom extends Notification
{
    /**
     * The password reset token.
     *
     * @var string
     */
    public $token;

    /**
     * The callback that should be used to build the mail message.
     *
     * @var \Closure|null
     */
    public static $toMailCallback;

    /**
     * Create a notification instance.
     *
     * @param  string  $token
     * @return void
     */
    public function __construct($token)
    {
        $this->token = $token;
    }

    /**
     * Get the notification's channels.
     *
     * @param  mixed  $notifiable
     * @return array|string
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Build the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        if (static::$toMailCallback) {
            return call_user_func(static::$toMailCallback, $notifiable, $this->token);
        }

        return (new MailMessage)
            ->subject(Lang::getFromJson('message.mail.password_reset.title'))
            ->line(Lang::getFromJson('message.mail.password_reset.line'))
            ->action(Lang::getFromJson('message.mail.password_reset.action'), url(config('app.url').route('password.reset', $this->token, false)))
            ->line(Lang::getFromJson('message.mail.password_reset.out_line1', ['count' => config('auth.passwords.users.expire')]))
            ->line(Lang::getFromJson('message.mail.password_reset.out_line2'));
    }

    /**
     * Set a callback that should be used when building the notification mail message.
     *
     * @param  \Closure  $callback
     * @return void
     */
    public static function toMailUsing($callback)
    {
        static::$toMailCallback = $callback;
    }
}

翻訳ファイルは

<?php

return [
    // メール
    "mail" => [
        // パスワードリセット
        "password_reset" => [
            "title" => "パスワードリセットのお知らせ",
            "line" => "パスワードリセットの受け付けました。",
            "action" => "パスワードリセット",
            "out_line1" => "こちらのパスワードリセットの有効期限は :count 分です。",
            "out_line2" => "こちらのメールに身に覚えがない場合は、無視をしてください。"
        ]
    ],
];

以上、パスワードリセットの日本語化は終わりです。

Laravelはtraitを多様していますので、何かあればその中身を調査するようにしています(ーー;

3
3
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
3
3