Why do you need Laravel Queue?
When we build a web application, some tasks take too much time such as emailing new users, reading CSV files, and many more. But Laravel provides a queued job. Queue job is running all processes in the background. By moving time-intensive tasks to a queue, your application can respond to web requests with blazing speed and provide a better user experience to your users.
Steps to implement Queue in Laravel
In order to use the database queue driver, you will need a database table to hold the jobs. Typically, this is included in Laravel’s default 0001_01_01_000002_create_jobs_table.php
Step 1: Setup Queue Configuration
A database table is required to hold the jobs with the database queue driver. To generate a migration that creates this table, run the below Artisan command.
php artisan queue:table
After the migration is created, migrate your database using the following command:
php artisan migrate
Step 2: Creating Jobs
By default, all queued jobs are stored in the app/Jobs directory. To create new Jobs, run the following artisan command into your terminal.
php artisan make:job NewUserWelcomeMail
This command creates the App/Jobs/NewUserWelcomeMail class which extends the Illuminate\Contracts\Queue\ShouldQueue interface. Indicating to Laravel that the job should be pushed onto the queue to run asynchronously.
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
class NewUserWelcomeMail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $user;
/**
* Create a new job instance.
*/
public function __construct($user)
{
$this->user = $user;
}
/**
* Execute the job.
*/
public function handle(): void
{
try {
Mail::send('emails', ['user' => $this->user], function ($email) {
$email->from('noreply@demo.com','Your App Name');
$email->to('test@yopmail.com')->subject('Congratulations!!');
});
} catch (\Throwable $th) {
// to keep track of error log, if it comes in sending email
Log::info('ERROR SENDING MAIL => ', [$th->getMessage()]);
}
}
}
In the above Mail::send() function the first argument is for your view file which is your blade file, i have created it in views/emails.blade.php and second argument is user which we will use in blade file as $user. See below code of blade file from which you can get an idea.
emails.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Welcome Email</title>
</head>
<body>
<div>
<br/>
<br/>
Hi, {{ $user->name }}
<br/>
<br/>
Greetings!! Welcome
<br/>
</div>
</body>
</html>
Step 3: Dispatch Queue Jobs
Here we create a user controller for creating users. It will look like the one below. When request comes in store method our job dispatch code will execute and it will make new entry in jobs table.
public function store(Request $request)
{
// validate your request
// create a user
$user = User::create([
"name"=> $request->name,
"email" => $request->email,
"password" => 'test@123'
]);
// dispatch your queue job
dispatch(new NewUserWelcomeMail($user));
return redirect()->back();
// return your response
}
Step 4: Running Queue Jobs
Laravel includes an Artisan command that will start a queue worker and process new jobs as they are pushed onto the queue. You may run the worker using the below Artisan command.
php artisan queue:work
Alternatively, you may run the queue:listen command. When using the queue:listen command, you don’t have to manually restart the worker when you want to reload your updated code or reset the application state.
php artisan queue:listen
That’s it. Now your welcome mail will be delivered after the response was delivered to the browser. The mail process works in the background.
What should we do if Queue fails?
A migration to create the failed_jobs table is typically already present in new Laravel applications. However, if your application does not contain a migration for this table, you may use the make:queue-failed-table command to create the migration:
php artisan make:queue-failed-table
php artisan migrate
You will get entries in the failed_jobs table with the exception occurring if our job fails.
Please take note: the value below needs to be changed to database in your .env file.
QUEUE_CONNECTION="databse"
Please click this link to learn how to set it up in a production setting.