laravellaravel-8laravel-queuelaravel-jobs

How to dispatch a chained job in a loop?


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++;
}

Solution

  • 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'));