Home / Snippets / Run Laravel Jobs in Sequence with Job Chaining
Run Laravel Jobs in Sequence with Job Chaining cover

Run Laravel Jobs in Sequence with Job Chaining

2.4K

3 years ago

0 comments

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();
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this