I just upgraded to Laravel 5.7 and now I am using the built in Email Verification. However there is 2 things I have not been able to figure out and the primary issue is how can I customize the email that is being sent to the user for verifying their email? I also can't figure out how to initiate sending that email if the users changes their email but I can save that for another thread.
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. Second, a route will be needed to handle requests generated when the user clicks the email verification link in the email.
When you want to add Email Verification in Laravel 5.7 the suggested method is to implement Illuminate\Contracts\Auth\MustVerifyEmail
and use the Illuminate\Auth\MustVerifyEmail
trait on the App\User
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 Notifications\MustVerifyEmail
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 App\Notifications\CustomVerifyEmail); }
...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 Illuminate\Auth\Events\Registered
Event is emitted in the App\Http\Controllers\Auth\RegisterController
and that Registered
event has a listener called Illuminate\Auth\Listeners\SendEmailVerificationNotification
which is registered in the App\Providers\EventServiceProvider
:
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 App\Http\Controllers\Auth\RegisterController
– is an instance of Illuminate\Contracts\Auth\MustVerifyEmail
which is the name of the trait that Laravel suggests is used in the App\User
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With