Skip to content

Instantly share code, notes, and snippets.

@albofish
Last active May 4, 2022 03:02
Show Gist options
  • Save albofish/c496bfa9183556155a18 to your computer and use it in GitHub Desktop.
Save albofish/c496bfa9183556155a18 to your computer and use it in GitHub Desktop.
Laravel Chunk Results to CSV
<?php
/*
* Chunk through result set and output as CSV file in browser.
*/
function outputCSV($columns, $query, $chunkSize = 200) {
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename='export-" . date("YmdHis") . ".csv");
header("Pragma: no-cache");
header("Expires: 0");
$output = fopen("php://output", "w");
fputcsv($output, $columns);
$query->select($columns)->chunk($chunkSize, function($rows) use(&$output) {
foreach ($rows as &$row) {
fputcsv($output, (array) $row);
}
});
fclose($output);
}
// Eloquent or Fluent DB query
$query = DB::table('users');
$columns = ['id', 'name', 'email'];
outputCSV($columns, $query);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment