People searching “Laravel chunk export” call chunk() inside a controller and the request times out. A download the user is waiting on should stream, which is the CSV page’s job. A file you email later belongs in a queued job. The queue guide is how that job gets on the page.
TL;DR
- chunkById walks a table in a job.
- Do not chunk() an update, and do not do this work inside the HTTP request.
- Do not
Post::all()and thencollect()->chunk()to feel safer. - Do not start this from a Vue
setInterval.
The fix#
Post::query()->orderBy('id')->chunkById(200, function ($posts) {
foreach ($posts as $post) {
// append a row to the export, or dispatch a smaller job
}
});chunkById remembers the last id. chunk() uses offset. If you delete or update rows inside chunk(), pages get skipped. That is the bug.
What to avoid#
Gotcha
Do not Post::all() and then collect()->chunk() to feel safer. You already loaded the table. Do not start this from a Vue setInterval. The button dispatches one job.
FAQ#
How do I chunk a large export in a job?
chunkById walks a table in a job. Do not chunk() an update, and do not do this work inside the HTTP request.
What goes wrong with Laravel chunk export?
Many developers call chunk() inside a controller and the request times out. Do not Post::all() and then collect()->chunk() to feel safer.



