Skip to content

Instantly share code, notes, and snippets.

@jackabox
Created April 10, 2018 09:18
Show Gist options
  • Select an option

  • Save jackabox/1149b40a682fb3b6280f54c6dfd501a2 to your computer and use it in GitHub Desktop.

Select an option

Save jackabox/1149b40a682fb3b6280f54c6dfd501a2 to your computer and use it in GitHub Desktop.
Generate a CSV and provide it for download with a response in Laravel 5
<?php
public function export()
{
$headers = [
'Content-type' => 'text/csv',
'Content-Disposition' => 'attachment; filename=users.csv',
'Pragma' => 'no-cache',
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Expires' => '0'
];
$users = User::all();
$columns = [
'UserID',
'Name',
'Email',
'StripeID',
'TrialEndsAt',
'Verified',
'Banned',
'Disabled',
'Created',
'RenewWarning'
];
$callback = function () use ($users, $columns) {
$this->generateCsv($users, $columns);
};
return Response::stream($callback, 200, $headers);
}
protected function generateCsv($users, $columns)
{
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
foreach ($users as $user) {
fputcsv($file, [
$user->id,
$user->name,
$user->email,
$user->stripe_id,
$user->trial_ends_at,
$user->verified,
$user->banned,
$user->disabled,
$user->created,
$user->renew_warning
]);
}
fclose($file);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment