Skip to content

Commit

Permalink
[9.x] Enable dispatchAfterResponse for batch 🔥 (#41787)
Browse files Browse the repository at this point in the history
* [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]>
  • Loading branch information
civilcoder55 and taylorotwell authored Apr 4, 2022
1 parent 0ce1f41 commit a3f49a6
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/Illuminate/Bus/PendingBatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -271,4 +271,49 @@ public function dispatch()

return $batch;
}

/**
* Dispatch the batch after the response is sent to the browser.
*
* @return \Illuminate\Bus\Batch
*/
public function dispatchAfterResponse()
{
$repository = $this->container->make(BatchRepository::class);

$batch = $repository->store($this);

if ($batch) {
$this->container->terminating(function () use ($batch) {
$this->dispatchExistingBatch($batch);
});
}

return $batch;
}

/**
* Dispatch an existing batch.
*
* @param \Illuminate\Bus\Batch $batch
* @return void
*
* @throws \Throwable
*/
protected function dispatchExistingBatch($batch)
{
try {
$batch = $batch->add($this->jobs);
} catch (Throwable $e) {
if (isset($batch)) {
$batch->delete();
}

throw $e;
}

$this->container->make(EventDispatcher::class)->dispatch(
new BatchDispatched($batch)
);
}
}

0 comments on commit a3f49a6

Please sign in to comment.