Posts Learn Components new Snippets new Categories Tags About
/

Run Laravel Jobs in Sequence with Job Chaining

Learn how to define Laravel Job in sequence with the Bus facade to chain jobs

Created on Sep 24, 2021

54 views

To run jobs in sequence order in Laravel you can make use of Job chaining. To achieve this you will have to make use of the Bus facade and calling the "chain" method.
By making use of this method if one job fails to process the whole sequence will fail to process hence making the flow optimal for processing subsequence tasks.

Laravel Bus Chain


To define the jobs you can define the code as follows.
<?php

use App\Jobs\ProcessImage;
use App\Jobs\OptimseImage;
use App\Jobs\ReleaseImage;
use Illuminate\Support\Facades\Bus;

Bus::chain([
    new ProcessImage,
    new OptimseImage,
    new ReleaseImage,
])->dispatch();

Passing Closure to Jobs Chain


To pass a closure to the jobs chain you can define your code like below.
<?php

Bus::chain([
    new ProcessImage,
    new OptimseImage,
    function () {
        Image::update(...);
    },
])->dispatch();

Chain Connection and Queue in Laravel


To specify the connection and queue in the Jobs chain you can chain the method using the "onConnection" and "onQueue" and passing the value as the method parameter.
<?php

Bus::chain([
    new ProcessImage,
    new OptimseImage,
    new ReleaseImage,
])->onConnection('redis')->onQueue('podcasts')->dispatch();
Do note that you can also catch any failed job using the "catch" method.
<?php

Bus::chain([
    new ProcessImage,
    new OptimseImage,
    new ReleaseImage,
])
->onConnection('redis')
->onQueue('podcasts')
->catch(function (Throwable $e) {
    // A job within the chain has failed...
})
->dispatch();
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻