Laravel Jobs and Queues with Example

Hello artisans, in this article I’m going to share Laravel jobs and queues with example. Let’s get started:

Note: Last tested on Laravel 8.62.0.

Table of Contents

  1. Install Laravel and Basic Config
  2. Configure Queue
  3. Create a Mailable Class
  4. Create a Queue Job
  5. Call Queue Job
  6. Test Queue Job

Install Laravel and Basic Config

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.

Configure Queue

We need to select a queue driver and need to generate a queues table. There are some drivers available such as sync, database, redis, sqs etc. We are going to use database driver.

Open .env file and change QUEUE_CONNECTION=sync to QUEUE_CONNECTION=database.

To create queues table, run this command:

php artisan queue:table

Then we need to migrate the database.

php artisan migrate

Create a Mailable Class

Before creating a mailable class, let’s set email SMTP credentials in the .env file. I’m using https://mailtrap.io/ SMTP service for sending emails.

.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=48********
MAIL_PASSWORD=6c********
MAIL_ENCRYPTION=tls
[email protected]

Now create a mailable class named SendEmailWelcome. In the terminal, type the following command.

php artisan make:mail SendEmailWelcome

Then open app/Mail/SendEmailWelcome.php file and paste the code:

SendEmailWelcome.php
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class SendEmailWelcome extends Mailable
{
    use Queueable, SerializesModels;

    private $name;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('Welcome to Shouts.dev!')->view('emails.welcome')->with([
            'name' => $this->name,
        ]);
    }
}

Now we need to create an email view. Create a view file in this location resources/views/emails/welcome.blade.php and paste the code:

welcome.blade.php
<!DOCTYPE html>
<html lang="en">
<body>
<h4>Laravel Jobs and Queues with Example - Shouts.dev</h4>
<p>Hello {{$name}}.</p>
<p>Welcome to Shouts.dev.</p>
</body>
</html>

Create a Queue Job

Let’s create a job to send welcome email.

php artisan make:job SendWelcomeEmailJob

Open app\Jobs\SendWelcomeEmailJob.php and paste this code:

SendWelcomeEmailJob.php
<?php

namespace App\Jobs;

use App\Mail\SendEmailWelcome;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

class SendWelcomeEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $details;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Mail::to($this->details['email'])->send(new SendEmailWelcome($this->details['name']));
    }
}

Call Queue Job

To test the queue job, we need to call the job. Open web route file and paste the code:

web.php
use App\Jobs\SendWelcomeEmailJob;

Route::get('test', function () {
    $details['name'] = 'Md Obydullah';
    $details['email'] = '[email protected]';

    dispatch(new SendWelcomeEmailJob($details));

    dd('sent');
});

You can call the job from anywhere such as from the controller.

Test Queue Job

Our app is ready to test. Before running the app, let’s clear the config:

php artisan optimize && php artisan config:clear

Now run the app:

php artisan serve

And visit http://localhost:8000/test to fire the job.

After firing the job, run this command in the console to process the queue job:

php artisan queue:work

If everything is okay, you’ll see the output like:

[2021-09-29 08:04:51][15] Processing: App\Jobs\SendWelcomeEmailJob
[2021-09-29 08:04:55][15] Processed:  App\Jobs\SendWelcomeEmailJob

Note: You can keep running the command php artisan queue:work using Task Scheduling.

That’s all. You can download this project from GitHub. Thanks for reading.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.