Created
April 10, 2018 09:18
-
-
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
This file contains hidden or 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
| <?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