How to Queue Verification Email in Laravel


- Step 1: Create a Queueable VerifyEmail Class
- Step 2: Tell Laravel to Use the New Notification
- Step 3: Configure the Queue System
- Conclusion
By default, Laravel sends the email verification notification synchronously when a user registers. This can slow down the registration process. A better approach is to queue the verification email, allowing the request to complete faster while the email is sent in the background. In this article, we’ll explore how to achieve that by creating a queueable VerifyEmail
class and updating the User
model to use it.
VerifyEmail
Class
Step 1: Create a Queueable Laravel uses the Illuminate\Auth\Notifications\VerifyEmail
notification to send verification emails. We will extend this class and make it queueable.
Run the following command to generate a new notification class:
php artisan make:notification QueueableVerifyEmail
Now, open app/Notifications/QueueableVerifyEmail.php
and modify it as follows:
<?php namespace App\Notifications; use Illuminate\Auth\Notifications\VerifyEmail;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue; class QueueableVerifyEmail extends VerifyEmail implements ShouldQueue{ use Queueable;}
This ensures that the notification is queued when dispatched.
Step 2: Tell Laravel to Use the New Notification
Next, we need to update the User
model to use our new QueueableVerifyEmail
class instead of the default VerifyEmail
notification.
Open app/Models/User.php
and override the sendEmailVerificationNotification
method:
public function sendEmailVerificationNotification(){ $this->notify(new \App\Notifications\QueueableVerifyEmail);}
Now, Laravel will send the verification email using the queued version of the notification.
Step 3: Configure the Queue System
To make sure queued jobs are processed, you need to configure Laravel’s queue system. If you haven't set up a queue driver yet, update your .env
file:
QUEUE_CONNECTION=database
Then, create the necessary database tables for queued jobs:
php artisan queue:tablephp artisan migrate
Finally, start the queue worker:
php artisan queue:listen
Conclusion
By following these steps, Laravel will now queue the verification email when a user registers, improving performance by handling email delivery in the background. This simple adjustment can significantly enhance the user experience by making registration faster and more efficient.
Stay Updated.
I'll you email you as soon as new, fresh content is published.