#Passing different constructor to each job in the chain

10 messages · Page 1 of 1 (latest)

left umbra
#

Hello, as stated I'm trying to push Jobs using Bus::chain.
Altho, I'd like to use different arguments to each job even if it's same chain.

It looks like something like this is NOT CORRECT

$articles = Article::all();
$jobs = [];
foreach($articles as $article) {
  $job = new CustomJob($article);
  array_push($jobs, $job);
}
Bus::chain($jobs)->dispatch();

But instead the arguments should be in the dispatch function.

Is there a way to chain jobs with different arguments?

iron pollen
#

you can just put different arguments into the constructor of the job. When dispatching a job outside of a bus calling Job::dispatch($args) is the same as calling dispatch(new Job($args))

left umbra
#

I probably didn't understand you answer, I'm sorry

iron pollen
#

just pass different args when you call new CustomJob($article)

left umbra
#

If I dispatch the jobs individually it's all ok, if I put them in a chain then they break with the following error:
TypeError: array_merge(): Argument #1 must be of type array, null given in /home/***/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php:121

iron pollen
#

try this

Bus::chain(
   Article::all()->map(fn($article) => new CustomJob($article))
)
->dispatch();
#

should do the same thing as your existing code but its cleaner

left umbra
#

I'll try thanks

#

same error 😦

#

But It might be related to something else... I'll double check other things