LoginSignup
6
9

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-02-01

こちらの内容はブログの方にも記載しています。

アプリ開発でメールアドレスが本当に登録してきたユーザー本人のものかを確認するときがあると思います。

Laravel5.7からMustVerifyEmailというの追加になったようで簡単に実装することができましたので簡単にまとめてます。

メールアドレス確認の実装

認証の準備

まずは認証の準備をします。以下のコマンドで簡単に作成できます。

php artisan make:auth
php artisan migrate

モデル

App\UserモデルにMustVerifyEmailインタフェースを設定します

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    // ...
}

ルートの設定

まずメールアドレス確認をするAuth\VerificationControllerを認証ルートに追加します。

Auth::routes(['verify' => true]);

これでメールアドレス確認ができるようになったので、ルートを保護します。

Route::get('profile', function () {
    // Only verified users may enter...
})->middleware('verified');

メール送信の設定

mailtrap

テスト中に間違ってメールを送ってしまわないように、mailtrapを利用して実際にはメールを送信して内容が確認できるようにします。

無料でも十分利用できますので、以下のサイトから登録してください

https://mailtrap.io/

.envファイルの設定

mailtrapの接続情報を確認して.envファイルに設定します。

日本語化

ここまででも利用できますが、画面内の文言やメールが英語なので日本語に変更します。

ビュー

php artisan make:auth でビューがresources/views/auth/verify.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.Verify.Title') }}</div>

                <div class="card-body">
                    @if (session('resent'))
                        <div class="alert alert-success" role="alert">
                            {{ __('message.Verify.NewUrl') }}
                        </div>
                    @endif

                    {{ __('message.Verify.SendActionUrl') }}<br/>
                    @lang('message.Verify.NotEmail', ['url' => route('verification.resend')])
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

メール本文の変更

Illuminate/Auth/MustVerifyEmail.phpの中身を確認するとsendEmailVerificationNotificationの中でメールを送っていましたので、カスタマイズしたNotificationを送信するように変更します。

まずはNotificationを作成します。

php artisan make:notification VerifyEmailCustom

中身はVerifyEmail.phpの中身をそのままコピーして、英語の部分を日本語にします。

<?php

namespace App\Notifications;

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

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

    /**
     * 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);
        }

        return (new MailMessage)
            ->subject(Lang::getFromJson('message.Mail.Verify.Title'))
            ->line(Lang::getFromJson('message.Mail.Verify.Line'))
            ->action(
                Lang::getFromJson('message.Mail.Verify.Action'),
                $this->verificationUrl($notifiable)
            )
            ->line(Lang::getFromJson('message.Mail.Verify.OutLine'));
    }

    /**
     * Get the verification URL for the given notifiable.
     *
     * @param  mixed  $notifiable
     * @return string
     */
    protected function verificationUrl($notifiable)
    {
        return URL::temporarySignedRoute(
            'verification.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]
        );
    }

    /**
     * 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;
    }
}

Userモデル

UserモデルでsendEmailVerificationNotificationをオーバーライドして、カスマイズしたNotificationを送信するようにします。

    public function sendEmailVerificationNotification()
    {
        $this->notify(new VerifyEmailCustom);
    }

通知メールの変更

このままでも通知メールのレイアウト部分が英語のままなので、そちらも日本語にします。

以下のコマンドでレイアウトを変更できるようにします。

php artisan vendor:publish

resources/views/notifications/email.blade.phpファイルができるので、中身を変更します。

@component('mail::message')
{{-- Greeting --}}
@if (! empty($greeting))
# {{ $greeting }}
@else
@if ($level === 'error')
# @lang('message.Mail.Whoops')
@else
# @lang('message.Mail.Opning')
@endif
@endif

{{-- Intro Lines --}}
@foreach ($introLines as $line)
{{ $line }}

@endforeach

{{-- Action Button --}}
@isset($actionText)
<?php
    switch ($level) {
        case 'success':
        case 'error':
            $color = $level;
            break;
        default:
            $color = 'primary';
    }
?>
@component('mail::button', ['url' => $actionUrl, 'color' => $color])
{{ $actionText }}
@endcomponent
@endisset

{{-- Outro Lines --}}
@foreach ($outroLines as $line)
{{ $line }}

@endforeach

{{-- Salutation --}}
@if (! empty($salutation))
{{ $salutation }}
@else
@lang('message.Mail.Regards')<br>{{ config('app.name') }}
@endif

{{-- Subcopy --}}
@isset($actionText)
@component('mail::subcopy')
@lang(
"message.Mail.NotClick",
[
    'actionText' => $actionText,
    'actionURL' => $actionUrl,
]
)
@endcomponent
@endisset
@endcomponent

日本語化ファイル

日本語のファイルをresources/lang/ja/message.phpに設定します。

<?php

return [
    // メールアドレスの確認
    "Verify" => [
        "Title" => "メールアドレスの確認",
        "NewUrl" => "新しく確認用のURLを送信しました。",
        "SendActionUrl" => "送られたメールを確認してURLをクリックして下さい。",
        "NotEmail" => "メールが届いていない場合は、<a href=':url'>こちら</a>をクリックして下さい。"
    ],

    // メール
    "Mail" => [
        "Opning" => "ご利用ありがとうございます。",
        "Whoops" => "ご迷惑をおかけいたします。",
        "Regards" => "引き続きのご利用をよろしくお願いいたします。",
        "NotClick" =>"「:actionText」がクリックできない場合は以下のURLをブラウザにコピーして下さい。\n[:actionURL](:actionURL)",

        // メールアドレスの確認
        "Verify" => [
            "Title" => "メールアドレスの確認",
            "Line" => "メールアドレスを確認するには、下のボタンをクリックしてください。",
            "Action" => "メールアドレスを確認",
            "OutLine" =>"アカウントを作成しなかった場合、それ以上の操作は必要ありません。"
        ]
    ]
];

参考

https://blog.capilano-fw.com/?p=289#i-7
https://blog.capilano-fw.com/?p=1099#i-7
6
9
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
6
9