2

I am trying to dispatch a Laravel job inside a foreach loop. But the problem is, when I dispatch job inside loop sometimes it is completed before jobs queued before it are completed. What I want that is jobs should be completed one by one. Like happens in the chain method. But How I chain the same job inside the foreach loop? Is this possible?

foreach ($consignments as $consignment) {
     CalculateSingleConsignment::dispatch($consignment, $total_consignments, $i, $user_id, $notify)->onQueue('invoice');
     $i++;
}
apokryfos
  • 38,771
  • 9
  • 70
  • 114

1 Answers1

5

You can construct the array to be chained rather than dispatching the actual job in the loop:

$jobs = [];
 foreach (array_values($consignments) as $i => $consignment) { 
      $jobs[] = new CalculateSingleConsignment($consignment, $total_consignments, $i, $user_id, $notify);
}
Bus::chain($jobs)->onQueue('invoice')->dispatch()

If you want to use dependency injection you can construct your jobs as:

app()->makeWith(CalculateSingleConsignment::class, compact('consignment', 'total_consignments', 'i', 'user_id', 'notify'));

apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • Can i use only first code for jobs . without dependency injection? –  Jan 21 '21 at 07:24
  • And what is `Bus` –  Jan 21 '21 at 07:25
  • `Illuminate\Support\Facades\Bus` (according to https://laravel.com/docs/8.x/queues#job-chaining), and yes you don't need to use dependency injection if your jobs don't need it – apokryfos Jan 21 '21 at 07:43