Intro

Laravel queues help process time-consuming tasks in the background
improving application performance. Two essential concepts this context are Bus and Chain, which allow job control and chaining.

In this guide, we will explore how to use Bus and Chain to create efficient execution flows in laravel.

Laravel Bus: dispatching multiple jobs

Bus allows dispatching multiple jobs simultaneously, without a specific execution order. Each job is processed independently.

Usage Example

<?php

use App\Jobs\ProcessOrder;
use App\Jobs\SendNotification;
use Illuminate\Support\Facades\Bus;

Bus::batch([
    new ProcessOrder($orderId),
    new SendNotification($userId)
])->dispatch();

Benefits of Bus

  • Useful for running independent tasks simultaneously.
  • Integration with Bus::batch allows tracking the batch job status.
  • Enables parallel execution of multiple jobs.

Monitoring Batch Jobs

Laravel allows monitoring and handling job batch using Bus::batch(). We can add callbacks to track.

<?php

Bus::batch([
    new ProcessOrder($orderId),
    new SendNotification($userId)
])->then(function (Batch $batch) {
    Log::info('All batch jobs have been completed.');
})->catch(function (Batch $batch, Throwable $e) {
    Log::error('Error in a batch job: ' . $e->getMessage());
})->dispatch();

Laravel Chain: Chaining Jobs

The Chain allows defining a sequence of job execution ensuring that the next job only runs if the previous one completes successfully.

Usage Example


<?php

use App\Jobs\ProcessPayment;
use App\Jobs\GenerateInvoice;
use App\Jobs\SendEmailReceipt;
use Illuminate\Support\Facades\Bus;

Bus::chain([
    new ProcessPayment($orderId),
    new GenerateInvoice($orderId),
    new SendEmailReceipt($userId)
])->dispatch();
  • Allows conditional job chaining within the flow.
  • Ensures sequential execution of jobs.
  • Useful for processes that require a specific order.

Handling Failures in Chained Jobs

If a job within a Chain fails, the subsequent jobs will not executed. To avoid this we can define failure handling.

<?php

Bus::chain([
    new ProcessPayment($orderId),
    new GenerateInvoice($orderId),
    new SendEmailReceipt($userId)
])->catch(function (Throwable $e) {
    Log::error('Queue processing error: ' . $e->getMessage());
});

Resilient Jobs

To ensure resilience, we can configure automatic retries for failing jobs:


<?php
class ProcessPayment implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;
    public $backoff = 10; // Wait time between retry attempts in seconds
}

Conclusion

  • Use Chain when you need sequential execution.
  • Use Bus when you need to dispatch multiple jobs in parallel.
  • Handle failures and implement automatic retries.

Laravel Queues make applications more efficient by prevint long processes from impacting user experience.

Author Of article : Aleson França Read full article