Creating a Queue Job in Laravel 11
Let’s create a class file for Queue Job by entering the following command
php artisan make:job Send
OtpEmail
To get the email data, just replace the construct method like below in Send
OtpEmail job class file
public function __construct(
public array $data
){}
Write the email sending code in handle() method of Send
OtpEmail job class file
public function handle(): void
{
// get data
$email = $this->data['email'];
$otp = $this->data['otp'];
// Email sending code here
...
}
The class file is ready to receive the job request and sending email.
Now, let’s open the OtpEmailController file and add the Job Class for sending request
use App\Jobs\SendOtpEmail;
Create a send method in the above OtpEmailController file as below
public function send()
{
// Email data
$data = [
'email' => '[email protected]',
'otp' => 1234 // generated otp
];
// Dispatch the job with data to queue
SendOtpEmail::dispatch($data)->onQueue('otpemails');
}
That’s it. It is now ready to send the request.
Now, enter the following command to start sending queued job. The otpemails will be sent earlier here.
php artisan queue:work --queue=otpemails,default