Skip to content

Commit a3f49a6

Browse files
[9.x] Enable dispatchAfterResponse for batch 🔥 (#41787)
* [9.x] Enable dispatchAfterResponse for batch 🔥 [before] batch can't be dispatched after response sent to user. [after] batch can be dipatched and all jobs will be saved to storage after response. - added dispatchAfterResponse method to: 1- store batch itself into database 2- register a terminating callback to dispatch batch jobs 3- return created batch - added private dispatchAlreadyCreated method to: 1- dispatch batch jobs and fire BatchDispatched event like before but without creating batch because we already created it in dispatchAfterResponse * formatting Co-authored-by: Taylor Otwell <[email protected]>
1 parent 0ce1f41 commit a3f49a6

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎src/Illuminate/Bus/PendingBatch.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,4 +271,49 @@ public function dispatch()
271271

272272
return $batch;
273273
}
274+
275+
/**
276+
* Dispatch the batch after the response is sent to the browser.
277+
*
278+
* @return \Illuminate\Bus\Batch
279+
*/
280+
public function dispatchAfterResponse()
281+
{
282+
$repository = $this->container->make(BatchRepository::class);
283+
284+
$batch = $repository->store($this);
285+
286+
if ($batch) {
287+
$this->container->terminating(function () use ($batch) {
288+
$this->dispatchExistingBatch($batch);
289+
});
290+
}
291+
292+
return $batch;
293+
}
294+
295+
/**
296+
* Dispatch an existing batch.
297+
*
298+
* @param \Illuminate\Bus\Batch $batch
299+
* @return void
300+
*
301+
* @throws \Throwable
302+
*/
303+
protected function dispatchExistingBatch($batch)
304+
{
305+
try {
306+
$batch = $batch->add($this->jobs);
307+
} catch (Throwable $e) {
308+
if (isset($batch)) {
309+
$batch->delete();
310+
}
311+
312+
throw $e;
313+
}
314+
315+
$this->container->make(EventDispatcher::class)->dispatch(
316+
new BatchDispatched($batch)
317+
);
318+
}
274319
}

0 commit comments

Comments
 (0)