Mobile Application Technology Web Application

How Do We Use Queue in Laravel?

Laravel Queue Banner

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:

sending email with queue

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));

}

3) 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:

send email job

4) 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

5) 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’);

});

}

6) 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 or you can  hire Laravel developers for any queries.

Want to read more Blogs ?

Similar Post

Certified By

OneClick

Got more questions? Chat with our experts or schedule a call back

Bot 14:52
Hi how can i help you?