How to Export CSV file in Laravel Example
In Laravel projects export csv and excel file from database more required. If you optate to exporting your data utilizing csv file in your projects version 5, 6 or 7 then here we make a simple step by step facile steps for export csv file utilizing php function not utilizing any library. In recent project we require to export the rows from the database in laravel but I checked in google more then sites utilizing library but if we engender csv utilizing php function then why we utilize any package. So guys lets start to export CSV Data in laravel example utilizing facile steps.
In first step you require to integrate a route in your web.php file.
Step 1: Add Route
1 2 |
Route::get('/tasks', 'TaskController@exportCsv'); |
Step 2: In Blade File
In this step add a export function in you js file to exporting data.
1 2 3 4 5 6 |
<script> function exportTasks(_this) { let _url = $(_this).data('href'); window.location.href = _url; } </script> |
Step 4: In your Controller
In last step you need to add a function to export rows in csv in laravel 5, 6 or 7 application. Here we get all projects but you can modify your code which you want to export you can add in column and tasks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public function exportCsv(Request $request) { $fileName = 'tasks.csv'; $tasks = Task::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('Title', 'Assign', 'Description', 'Start Date', 'Due Date'); $callback = function() use($tasks, $columns) { $file = fopen('php://output', 'w'); fputcsv($file, $columns); foreach ($tasks as $task) { $row['Title'] = $task->title; $row['Assign'] = $task->assign->name; $row['Description'] = $task->description; $row['Start Date'] = $task->start_at; $row['Due Date'] = $task->end_at; fputcsv($file, array($row['Title'], $row['Assign'], $row['Description'], $row['Start Date'], $row['Due Date'])); } fclose($file); }; return response()->stream($callback, 200, $headers); } |
i hope you like this article.