Exporting data to CSV is one of the many features most applications should have. Sometimes it would be a report for your marketing or finance team or a list of products in your inventory.
Step 1: Add Route
Route::get('export/customers','CustomerController@export');
Step 2: Add the below in your Controller
function export() { $fileName = 'customers.csv'; $customers = Customer::all(); $headers = array( "Content-type" => "text/csv", "Content-Disposition" => "attachment; filename=$fileName", "Pragma" => "no-cache", "Cache-Control" => "must-revalidate, post-check=0, pre-check=0", "Expires" => "0" ); $columns = array('Firstname', 'Lastname', 'Email', 'Created At'); $callback = function() use($customers, $columns) { $file = fopen('php://output', 'w'); fputcsv($file, $columns); foreach ($customers as $customer) { $row['firstname'] = $customer->firstname; $row['lastname'] = $customer->lastname; $row['email'] = $customer->email; $row['created_at'] = $customer->created_at; fputcsv($file, array($row['firstname'], $row['lastname'], $row['email'], $row['created_at'])); } fclose($file); }; return response()->stream($callback, 200, $headers); }
Next, go to the browser and access the URL, you will see the file is downloading to your computer.
Did this post help you?
Tutsplanet brings in-depth and easy tutorials to understand even for beginners. This takes a considerable amount of work. If this post helps you, please consider supporting us as a token of appreciation:
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply