Created
March 2, 2020 19:16
-
-
Save LarryBarker/26a4c66a97dde7479b7ed6551cb75608 to your computer and use it in GitHub Desktop.
Streaming Large CSV Files with chunk()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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