When you want to add Email Verification in Laravel 5.7 the suggested method is to implement IlluminateContractsAuthMustVerifyEmail
and use the IlluminateAuthMustVerifyEmail
trait on the AppUser
Model.
To make some custom behaviour you can override the method sendEmailVerificationNotification
which is the method that notifies the created user by calling the method notify
, and passes as a parameter a new instance of the NotificationsMustVerifyEmail
class.
You can create a custom Notification which will be passed as a parameter to the $this->notify()
within the sendEmailVerificationNotification method in your User Model:
public function sendEmailVerificationNotification()
{
$this->notify(new AppNotificationsCustomVerifyEmail);
}
...then in your CustomVerifyEmail
Notification you can define the way the verification will be handled. You can notify created user by sending an email with a custom verification.route which will take any parameters that you want.
Email verification notification process
When a new user signs-up an IlluminateAuthEventsRegistered
Event is emitted in the AppHttpControllersAuthRegisterController
and that Registered
event has a listener called IlluminateAuthListenersSendEmailVerificationNotification
which is registered in the AppProvidersEventServiceProvider
:
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
]
];
The SendEmailVerificationNotification
listener checks if the $user – which is passed as a parameter to new Registered($user = $this->create($request->all()))
in the Laravel default authentication AppHttpControllersAuthRegisterController
– is an instance of IlluminateContractsAuthMustVerifyEmail
which is the name of the trait that Laravel suggests is used in the AppUser
Model when you want to provide default email verification and also check that $user
is not already verified. If all that passes, the sendEmailVerificationNotification
method is called on that user:
if ($event->user instanceof MustVerifyEmail && !$event->user->hasVerifiedEmail()) {
$event->user->sendEmailVerificationNotification();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…