Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save LarryBarker/26a4c66a97dde7479b7ed6551cb75608 to your computer and use it in GitHub Desktop.
Save LarryBarker/26a4c66a97dde7479b7ed6551cb75608 to your computer and use it in GitHub Desktop.
Streaming Large CSV Files with chunk()
// See: https://medium.com/@barryvdh/streaming-large-csv-files-with-laravel-chunked-queries-4158e484a5a2
/*
* Response
*/
$response = new StreamedResponse(function() {
// Set the file name
$filename = 'claims.csv';
/*
* Prepare CSV
*/
$handle = fopen('php://output', 'w');
/*
* Add headers
*/
$headers = [];
$columns = $this->makeList('export')->getVisibleColumns();
foreach ($columns as $column) {
$headers[] = Lang::get($column->label);
}
fputcsv($handle, $headers);
/*
* Add records
*/
$query = $list->prepareQuery();
// Scope to user company
if (!$this->user->hasAccess('bg.company.manage_all_claims')) {
$query->forCompany($this->user->company->name);
}
$results = $query->chunk(1000, function ($result) use ($list, $handle, $columns) {
foreach ($result as $claim) {
$record = [];
foreach ($columns as $column) {
$value = $list->getColumnValueRaw($user, $column);
if (is_array($value)) {
$value = implode('|', $value);
}
$record[] = $value;
}
fputcsv($handle, $record);
}
});
fclose($handle);
}, 200, [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="claims.csv"',
]);
return $response;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment