Queues and Jobs

πŸ“˜ Laravel πŸ‘ 34 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

Queues and jobs in Laravel are used to handle time-consuming tasks in the background, improving application performance and user experience. Instead of executing heavy tasks during a request, Laravel allows them to run asynchronously using a queue system.


1. What Are Jobs?

A job is a class that contains the logic for a task that should be executed later or in the background.

Common examples:

  • Sending emails

  • Processing uploaded files

  • Generating reports

  • Sending notifications

Jobs are stored in:

app/Jobs

2. What Are Queues?

A queue is a mechanism that holds jobs until they are processed by a worker.

Benefits:

  • Faster response time

  • Better scalability

  • Improved user experience


3. Queue Configuration

Queue settings are located in:

config/queue.php

Common queue drivers:

  • sync (default – runs immediately)

  • database

  • redis

  • beanstalkd

  • sqs

Set the queue driver in .env:

QUEUE_CONNECTION=database

4. Database Queue Setup

To use the database driver:

php artisan queue:table php artisan migrate

This creates a jobs table.


5. Creating a Job

Create a job using Artisan:

php artisan make:job SendEmailJob

Example job:

use Illuminate\Contracts\Queue\ShouldQueue; class SendEmailJob implements ShouldQueue { public function handle() { // Task logic here } }

Implementing ShouldQueue tells Laravel to queue the job.


6. Dispatching Jobs

Dispatch a job to the queue:

SendEmailJob::dispatch();

With delay:

SendEmailJob::dispatch()->delay(now()->addMinutes(5));

7. Queue Workers

Queue workers process jobs:

php artisan queue:work

For continuous processing:

php artisan queue:listen

8. Failed Jobs

Failed jobs are stored for debugging.

Create failed jobs table:

php artisan queue:failed-table php artisan migrate

View failed jobs:

php artisan queue:failed

Retry failed job:

php artisan queue:retry 5

9. Job Timeout and Retries

Set retries and timeout in job:

public $tries = 3; public $timeout = 120;

10. Job Chaining and Batching

Job Chaining

Bus::chain([ new JobOne, new JobTwo, ])->dispatch();

Job Batching

Bus::batch([ new JobOne, new JobTwo, ])->dispatch();

Conclusion

Laravel’s queue and job system enables efficient background processing, improving application performance and scalability. By offloading heavy tasks to queues, developers can build faster and more responsive applications while maintaining clean and organized code.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes