Skip to content

Instantly share code, notes, and snippets.

@mnshankar
Forked from coreymcmahon/routes.php
Last active June 13, 2017 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnshankar/3be67edba81ae40f57aafb318248fb27 to your computer and use it in GitHub Desktop.
Save mnshankar/3be67edba81ae40f57aafb318248fb27 to your computer and use it in GitHub Desktop.
Using macros to implement custom response types in Laravel - www.slashnode.com
<?php
Response::macro('csv', function($data, $filename = 'data.csv', $status = 200, $delimiter = ",", $linebreak = "\n", $headers = array())
{
return Response::stream(function () use ($data, $delimiter, $linebreak) {
foreach ($data as $row) {
$keys = array(); $values = array();
$firstPassComplete = (isset($firstPassComplete)) ? true:false;
foreach ($row as $k => $v) {
if (!$firstPassComplete){
//get keys only on the first pass through array since it is repeated for every row
$keys[] = is_string($k) ? '"' . str_replace('"', '""', $k) . '"' : $k;
}
$values[] = is_string($v) ? '"' . str_replace('"', '""', $v) . '"' : $v;
}
if (count($keys) > 0) echo implode($delimiter, $keys) . $linebreak;
if (count($values) > 0) echo implode($delimiter, $values) . $linebreak;
}
}, 200, array_merge(array(
'Content-type' => 'text/csv',
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Description' => 'File Transfer',
'Content-Disposition' => 'attachment; filename=' . $filename,
'Expires' => '0',
'Pragma' => 'public',
), $headers));
});
Route::get('users', function () {
$users = Acme\Models\Users::get()->toArray();
return Response::csv($users);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment