Laravel Queue with Parameters Step by Step Example

The following steps should be followed to use a queue in Laravel.

Create a Job

Create a new job class by executing the following command:

php artisan make:job MyJob

To create a new job class in the app/Jobs directory, use the following command. After that, open the file and include the given code:

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

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

    private array $params;

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

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        dd($this->params);
    }
}

Add Job to Queue

In order to enqueue your job, you must invoke the dispatch() method of the job class.

$params = [
    'name' => 'John Doe',
    'email' => '[email protected]'
];

MyJob::dispatch($params);

Set up Queue Connection

In Laravel, it's possible to modify the QUEUE_CONNECTION setting to use any of the available drivers, including redis, sync, database, beanstalkd, sqs, iron, and rabbitmq. I'm using Redis.

QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

Process the Job

To process the jobs in the queue, you need to run the following command:

php artisan queue:work

Executing this instruction will initiate a worker task that will consistently monitor the queue for any incoming tasks that require processing.


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.