Email authentication
- Database Notes
- Email Verification Field
- Protected Route
- After email verification
Email Verification
Introduction
Many web applications require users to provide their email address before use verify. Rather than forcing you to implement it repeatedly in every application, Laravel provides convenient methods for sending and validating email authentication requests.
Model preparation
Before you start, you need to verify whether your
App\User
model implements theIlluminate\Contracts\Auth\MustVerifyEmail
contract:<?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; // ... }
Database Notes
Email Validation Field
Next, your
user
needs Contains anemail_verified_at
field to store the time when the email address was verified. By default, the data migration of theusers
table in the Laravel framework already includes this field. So, all you need to do is perform a database migration:php artisan migrate
Routing
Laravel's
Auth\VerificationController
class Contains the necessary logic for sending verification links and verification emails. By passing theverify
option to theAuth::routes
method, you can register the required routes for this controller:Auth::routes(['verify' => true]);
Protect Routes
Routing middleware can be used to allow only authenticated users to access specified routes. Laravel comes with the
verified
middleware, which is defined inIlluminate\Auth\Middleware\EnsureEmailIsVerified
. Since this middleware is already registered with your application's HTTP core, all you need to do is attach the middleware to the route definition:Route::get('profile', function () { // Only verified users may enter... })->middleware('verified');
View
Laravel will generate the view files necessary for email verification when you execute the
make:auth
command. The location of the view file isresources/views/auth/verify.blade.php
, you can freely adjust the style of these views according to your application.After email authentication
After email authentication, the user will automatically be redirected to
/home
. You can adjust the jump position after authentication by defining aredirectTo
method or attribute inVerificationController
.protected $redirectTo = '/dashboard';
Event
Laravel can trigger events during the verification process. You should register the listener in
EventServiceProvider
:/** * 应用程序的事件监听器 * * @var array */ protected $listen = [ 'Illuminate\Auth\Events\Verified' => [ 'App\Listeners\LogVerifiedUser', ], ];
This article was first published on the LearnKu.com website.