Readouble

Laravel 8.x メール確認

イントロダクションIntroduction

多くのWebアプリケーションでは、ユーザーがアプリケーションを使用開始する前に電子メールアドレスを確認する必要があります。Laravelでは、作成するアプリケーションごとにこの機能を手動で再実装する必要はなく、電子メール確認リクエストを送信および検証するための便利な組み込みサービスを提供しています。Many web applications require users to verify their email addresses before using the application. Rather than forcing you to re-implement this feature by hand for each application you create, Laravel provides convenient built-in services for sending and verifying email verification requests.

lightbulb">Tip!! てっとり早く始めたいですか?Laravelアプリケーションスターターキットの1つを新しいLaravelアプリケーションにインストールしてください。スターターキットは、電子メール確認サポートを含む、認証システム全体のスカフォールドを処理します。{tip} Want to get started fast? Install one of the Laravel application starter kits[/docs/{{version}}/starter-kits] in a fresh Laravel application. The starter kits will take care of scaffolding your entire authentication system, including email verification support.

モデルの準備Model Preparation

はじめる前に、App\Models\UserモデルがIlluminate\Contracts\Auth\MustVerifyEmail契約を実装していることを確認してください。Before getting started, verify that your App\Models\User model implements the Illuminate\Contracts\Auth\MustVerifyEmail contract:

<?php

namespace App\Models;

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

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    // ...
}

このインターフェイスをモデルへ追加したら、新しく登録したユーザーへ、確認リンクを含む電子メールが自動的に送信されます。アプリケーションのApp\Providers\EventServiceProviderを調べるとわかるように、はじめからLaravelは、Illuminate\Auth\Events\Registeredイベントへアタッチ済みのSendEmailVerificationNotificationリスナを用意してあります。このイベントリスナが、電子メール確認リンクをユーザーへ送信します。Once this interface has been added to your model, newly registered users will automatically be sent an email containing an email verification link. As you can see by examining your application's App\Providers\EventServiceProvider, Laravel already contains a SendEmailVerificationNotification listener[/docs/{{version}}/events] that is attached to the Illuminate\Auth\Events\Registered event. This event listener will send the email verification link to the user.

スターターキットを使用する代わりに、アプリケーション内で手動で登録を実装する場合は、ユーザーの登録が成功した後に、Illuminate\Auth\Events\Registeredイベントを確実に発行してください。If you are manually implementing registration within your application instead of using a starter kit[/docs/{{version}}/starter-kits], you should ensure that you are dispatching the Illuminate\Auth\Events\Registered event after a user's registration is successful:

use Illuminate\Auth\Events\Registered;

event(new Registered($user));

データベースの検討事項Database Preparation

次に、usersテーブルにユーザーの電子メールアドレスが確認された日時を格納するためのemail_verified_atカラムを用意する必要があります。デフォルトでLaravelフレームワークに含まれているusersテーブルのマイグレーションには、はじめからこのカラムが含まれています。したがって、必要なのはデータベースのマイグレーションを実行することだけです。Next, your users table must contain an email_verified_at column to store the date and time that the user's email address was verified. By default, the users table migration included with the Laravel framework already includes this column. So, all you need to do is run your database migrations:

php artisan migrate

ルートRouting

電子メール確認を適切に実装するには、3つのルートを定義する必要があります。第1に、Laravelがユーザー登録後に送信する確認メール中のメールアドレス確認リンクをクリックする必要があるという通知をユーザーに表示するためのルートが必要になります。To properly implement email verification, three routes will need to be defined. First, a route will be needed to display a notice to the user that they should click the email verification link in the verification email that Laravel sent them after registration.

第2に、ユーザーが電子メール内の電子メール確認リンクをクリックしたときに生成されるリクエストを処理するルートです。Second, a route will be needed to handle requests generated when the user clicks the email verification link in the email.

第3に、ユーザーが誤って最初の確認リンクを紛失した場合に、確認リンクを再送信するためのルートです。Third, a route will be needed to resend a verification link if the user accidentally loses the first verification link.

メール確認の通知The Email Verification Notice

前述のように、登録後にLaravelがメールで送信するメール確認リンクをクリックするようにユーザーに指示するビューを返すルートを定義する必要があります。このビューは、ユーザーが最初に電子メールアドレスを確認せずにアプリケーションの他の部分にアクセスしようとしたときに表示されます。App\Models\UserモデルがMustVerifyEmailインターフェイスを実装している限り、リンクは自動的にユーザーへ電子メールで送信されることに注意してください。As mentioned previously, a route should be defined that will return a view instructing the user to click the email verification link that was emailed to them by Laravel after registration. This view will be displayed to users when they try to access other parts of the application without verifying their email address first. Remember, the link is automatically emailed to the user as long as your App\Models\User model implements the MustVerifyEmail interface:

Route::get('/email/verify', function () {
    return view('auth.verify-email');
})->middleware('auth')->name('verification.notice');

メール確認通知を返すルートの名前は verification.noticeにする必要があります。Laravelが用意しているverifiedミドルウェアは、ユーザーがメールアドレスを確認していない場合、このルート名に自動的にリダイレクトするため、ルートへ正確にこの名前を割り当てることが重要です。The route that returns the email verification notice should be named verification.notice. It is important that the route is assigned this exact name since the verified middleware included with Laravel[#protecting-routes] will automatically redirect to this route name if a user has not verified their email address.

lightbulb">Tip!! 電子メール検証を手動で実装する場合は、検証通知ビューの内容を自分で定義する必要があります。必要なすべての認証ビューと検証ビューを含むスカフォールドが必要な場合は、Laravelアプリケーションスターターキットをチェックしてください。{tip} When manually implementing email verification, you are required to define the contents of the verification notice view yourself. If you would like scaffolding that includes all necessary authentication and verification views, check out the Laravel application starter kits[/docs/{{version}}/starter-kits].

メール確認のハンドラThe Email Verification Handler

次に、ユーザーが電子メールで送信された電子メール確認リンクをクリックしたときに生成されるリクエストを処理するルートを定義する必要があります。このルートにはverification.verifyという名前を付け、authおよびsignedミドルウェアを割り当てる必要があります。Next, we need to define a route that will handle requests generated when the user clicks the email verification link that was emailed to them. This route should be named verification.verify and be assigned the auth and signed middlewares:

use Illuminate\Foundation\Auth\EmailVerificationRequest;

Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
    $request->fulfill();

    return redirect('/home');
})->middleware(['auth', 'signed'])->name('verification.verify');

先に進む前に、このルートを詳しく見てみましょう。まず、通常のIlluminate\Http\Requestインスタンスの代わりにEmailVerificationRequestリクエストタイプを使用していることに気付くでしょう。EmailVerificationRequestは、Laravelに含まれているフォームリクエストです。このリクエストは、リクエストのidパラメータとhashパラメータの検証を自動的に処理します。Before moving on, let's take a closer look at this route. First, you'll notice we are using an EmailVerificationRequest request type instead of the typical Illuminate\Http\Request instance. The EmailVerificationRequest is a form request[/docs/{{version}}/validation#form-request-validation] that is included with Laravel. This request will automatically take care of validating the request's id and hash parameters.

次に、リクエスト上のfulfillメソッドを直接呼び出します。このメソッドは、認証済みユーザーのmarkEmailAsVerifiedメソッドを呼び出し、Illuminate\Auth\Events\Verifiedイベントを発行します。markEmailAsVerifiedメソッドは、Illuminate\Foundation\Auth\Userベースクラスを介してデフォルトのApp\Models\Userモデルで利用できます。 ユーザーのメールアドレスを検証したら、好きな場所にリダイレクトできます。Next, we can proceed directly to calling the fulfill method on the request. This method will call the markEmailAsVerified method on the authenticated user and dispatch the Illuminate\Auth\Events\Verified event. The markEmailAsVerified method is available to the default App\Models\User model via the Illuminate\Foundation\Auth\User base class. Once the user's email address has been verified, you may redirect them wherever you wish.

メール確認の再送信Resending The Verification Email

たまにユーザーはメールアドレスの確認メールを紛失したり、誤って削除したりすることがあります。これに対応するため、ユーザーが確認メールの再送信をリクエストできるルートを定義できます。次に、確認通知ビュー内にシンプルなフォーム送信ボタンを配置することで、このルートへのリクエストを行うことができるようにしましょう。Sometimes a user may misplace or accidentally delete the email address verification email. To accommodate this, you may wish to define a route to allow the user to request that the verification email be resent. You may then make a request to this route by placing a simple form submission button within your verification notice view[#the-email-verification-notice]:

use Illuminate\Http\Request;

Route::post('/email/verification-notification', function (Request $request) {
    $request->user()->sendEmailVerificationNotification();

    return back()->with('message', 'Verification link sent!');
})->middleware(['auth', 'throttle:6,1'])->name('verification.send');

保護下のルートProtecting Routes

ルートミドルウェアは、確認済みユーザーのみが特定のルートにアクセスできるようにするために使用できます。Laravelには、Illuminate\Auth\Middleware\EnsureEmailIsVerifiedクラスを参照するverifiedミドルウェアが付属しています。このミドルウェアはアプリケーションのHTTPカーネルではじめから登録されているため、必要なのはミドルウェアをルート定義にアタッチすることだけです。Route middleware[/docs/{{version}}/middleware] may be used to only allow verified users to access a given route. Laravel ships with a verified middleware, which references the Illuminate\Auth\Middleware\EnsureEmailIsVerified class. Since this middleware is already registered in your application's HTTP kernel, all you need to do is attach the middleware to a route definition:

Route::get('/profile', function () {
    // 確認済みのユーザーのみがこのルートにアクセス可能
})->middleware('verified');

このミドルウェアが割り当てられているルートに、未確認ユーザーがアクセスしようとすると自動的にverification.notice名前付きルートにリダイレクトされます。If an unverified user attempts to access a route that has been assigned this middleware, they will automatically be redirected to the verification.notice named route[/docs/{{version}}/routing#named-routes].

カスタマイズCustomization

確認メールのカスタマイズVerification Email Customization

デフォルトの電子メール確認通知はほとんどのアプリケーションの要件を満たすと思いますが、Laravelでは電子メール確認メールメッセージの構築をカスタマイズできます。Although the default email verification notification should satisfy the requirements of most applications, Laravel allows you to customize how the email verification mail message is constructed.

取り掛かるには、Illuminate\Auth\Notifications\VerifyEmail通知によって提供されるtoMailUsingメソッドにクロージャを渡します。クロージャは、通知を受信するnotifiableモデルインスタンスと、ユーザーがメールアドレスを確認するためにアクセスする必要のある署名済みのメール確認URLを受け取ります。クロージャは、Illuminate\Notifications\Messages\MailMessageのインスタンスを返す必要があります。通常、アプリケーションのApp\Providers\AuthServiceProviderクラスのbootメソッドからtoMailUsingメソッドを呼び出す必要があります。To get started, pass a closure to the toMailUsing method provided by the Illuminate\Auth\Notifications\VerifyEmail notification. The closure will receive the notifiable model instance that is receiving the notification as well as the signed email verification URL that the user must visit to verify their email address. The closure should return an instance of Illuminate\Notifications\Messages\MailMessage. Typically, you should call the toMailUsing method from the boot method of your application's App\Providers\AuthServiceProvider class:

use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Notifications\Messages\MailMessage;

/**
 * 全認証/認可サービスの登録
 *
 * @return void
 */
public function boot()
{
    // …

    VerifyEmail::toMailUsing(function ($notifiable, $url) {
        return (new MailMessage)
            ->subject('Verify Email Address')
            ->line('Click the button below to verify your email address.')
            ->action('Verify Email Address', $url);
    });
}

lightbulb">Tip!! メール通知の詳細は、メール通知ドキュメントを参照してください。{tip} To learn more about mail notifications, please consult the mail notification documentation[/docs/{{version}}/notifications#mail-notifications].

イベントEvents

Laravelアプリケーションスターターキットを使用する場合、Laravelはメール確認プロセス中にイベントを発行します。アプリケーションの電子メール確認を手動で処理する場合は、確認の完了後にこれらのイベントを手動で発行することを推奨します。アプリケーションのEventServiceProviderでこれらのイベントへリスナをアタッチできます。When using the Laravel application starter kits[/docs/{{version}}/starter-kits], Laravel dispatches events[/docs/{{version}}/events] during the email verification process. If you are manually handling email verification for your application, you may wish to manually dispatch these events after verification is completed. You may attach listeners to these events in your application's EventServiceProvider:

/**
 * アプリケーションにマップするイベントリスナ
 *
 * @var array
 */
protected $listen = [
    'Illuminate\Auth\Events\Verified' => [
        'App\Listeners\LogVerifiedUser',
    ],
];

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作