People waiting in a queue
,

How to use Laravel’s Job chaining

This is a personal one, I simply love how clean and simple this feature is.

In the past, I’ve had to implement job chaining and TBH the end result was pretty gross. It was a system that needed to take a file and pass it through a series of steps, so nothing too complex. But, by the way the chain worked, every job was conscious about the next one in line (sans the last one, of course).

But now, how Laravel does it allows us to completely decouple the jobs from each other. Yeah, I know, it’s awesome.

It looks like this:

FirstJobToRun::withChain([
    new SecondJobToRun,
    new ThirdJobToRun,
    new ForthJobToRun
])->dispatch();

So yes, it’s that simple. But if you are like me, simple is never enough cause of course you have that one case in which you need to pass arguments to your jobs. So, how about that? Well, thankfully it’s simple too.

Here in this example I’ve taken the one from the official docs and added a simple parameter:

ProcessPodcast::withChain([
    new OptimizePodcast($podcast),
    new ReleasePodcast($podcast)
])->dispatch($podcast);

And that’s all, now go read the official docs and then refactor all those tangled job chains that you’ve written before.

Thank you to all those who worked on this.

PD: Wouldn’t it be really cool if we could just define common arguments for all jobs in a chain?

Comments (

)