Laravel5.7に更新したら、会員登録時にEメール確認リンクを送信する新機能が追加されました。設定は簡単です。
流れ
まず、どういうものか、画面で流れ追ってみましょう。
このトップ画面から始まります。

右上のRegisterのリンクをクリックすると、会員登録画面になります。

情報を入力して、Registerボタンを押すと登録完了とともに、以下のメールが送信されます。

そこで、Verify Email Addressのボタンをクリックすると、以下の画面へ遷移してEメールの確認完了です。ログアウトしているなら、ログインをして成功したら確認完了です。

設定
この設定には、コマンドラインでまず以下を実行します。
$ php artisan make:auth
この実行により会員認証関連のファイルが作成されます。
次に、routes/web.phpファイルをエディターで開き、Auth::routes(['verify' => true])に編集します。
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes(['verify' => true]);
Route::get('/home', 'HomeController@index')->name('home');
次に、app/User.phpを編集します。
class User extends Authenticatable implements 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;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
これだけで設定完了です。
データベースの変更
このために、DBテーブル、usersに新規の項目、email_verified_atが追加されました。
会員登録時は、その項目の値は、nullです。
>>> User::find(1);
=> App\User {#3179
id: 1,
name: "kenji",
email: "kenji@example.com",
email_verified_at: null,
created_at: "2019-06-07 23:04:32",
updated_at: "2019-06-07 23:04:32",
}
しかし、Eメール確認後は、
>>> User::find(1);
=> App\User {#3179
id: 1,
name: "kenji",
email: "kenji@example.com",
email_verified_at: "2019-06-07 23:10:30",
created_at: "2019-06-07 23:04:32",
updated_at: "2019-06-07 23:04:32",
}
と確認時の日時が入ります。
Eメール確認した会員のみだけが閲覧できる
例えば、ECサイトなら、Eメールを確認した会員のみが注文ができる、とかに設定したいなら、カート画面に保護をかけることも可能です。
Route::get('cart', function () {
// Eメール確認した会員のみアクセス可能
})->middleware('verified');
まだ確認してない会員には、route('verification.notice')にレダイレクトして、Eメール確認メールの再送信を促すことも可能です。

