=>When we are sending multiple emails in laravel at one time, it takes a lot of time. This time-consuming process disturbs the user experience.=>For this problem we have one solution in laravel, which is called “Queue”. Queue place the task in sequential order and perform them one by one.
=>In case of sending multiple emails at one time Queue store the tasks in queue table and execute it one by one after some time (whenever we want).
In Depth…
The =>Queue config file is stored in config/queue.php, where you can find different connection configurations related to queue.
Example: How do we sending an email with a queue?
1) For sending an email we need to do below configuration in our .env file:
2) Create a controller:
php artisan make:controller EmailController
=>In this controller create a method which is having an email address in the request.
Public function sendEmail(Request $request)
{
/* This method will call SendEmailJob Job*/
dispatch(new SendEmailJob($request));
}
1) Create Job classes for Queue
=>For using queue we need to create Jobs, which defines the task to be done in the queue after later time.
=>By default, all Job classes are created in App/Jobs folder. For creating job classes run below command in terminal.
php artisan make: job SendEmailJob
=>This command creates a file in App/Jobs folder, which looks like:
2) Set a queue driver:
Drivers are stored pending queues temporarily. We will use the database driver as of now. To create a driver we need to run below command:
php artisan queue:table
php artisan migrate
=>We need to define our driver type in a .env file like this:
QUEUE_DRIVER = database
3) Define the queue’s task in Job class:
=>In SendEmailJob class we need to define our task in handle() method like:
public function handle()
{
$data = $this->details;
Mail::send([‘html’=>’demo_email_template’], $data, function($message) use ($data)
{
$message->to(‘receiver@gmail.com’, ‘John’)
->subject(‘This is test Queue.’);
$message->from(‘info@demo.com’,’LaravelQueue’);
});
}
4) In the end, you need to listen to the queue to do the queue jobs.
=> php artisan queue:listen
If you want to make this process automated then create a Scheduler and run this command in a particular time. So you don’t need to type this command every time.
=>You can see your pending jobs in jobs table also.
We are a mobile application, web, and software development company. Please feel free to contact us for any of your software queries.