Export CSV File in Laravel 7 Tutorial with Example Easy Steps

More then times we need to export our database data in csv file. In first time Export CSV File in Laravel 7 we use easy php function. Here we make a simple step by step easy way for export csv file using php function not used any library.

In recent project we need to export the rows from the database in laravel but I checked in google more then sites using library but if we generate csv using php function then why we use any package. So guys lets start to Export CSV File in Laravel 7 example using easy steps.

Step 1: Add Link in Blade File

In first step you need to add a link in your blade which data you want to export.

<a class="btn btn-success btn-sm mr-2" data-href="{{route('task.export')}}"
   href="javascript:void(0);"
   onclick="exportTasks(event.target);">Export</a>

Step 2: Add Route

Now add a route for exporting csv data in laravel 7.

Route::get('/export-tasks', 'TaskController@exportCsv')->name('task.export);

Step 3: In JS FIle

Call the function which is added in blade file link and redirect to controller.

<script>
   function exportTasks(_this) {
      let _url = $(_this).data('href');
      window.location.href = _url;
   }
</script>

Step 4: In your Controller

Here you need to add the below code where we getting the tasks records and then exporting it as a csv.

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);
    }

Read Here: Import CSV in Laravel 7

So, Today we learn how to export csv in laravel 7. Its very easy to exporting any record to csv in laravel. If you have any question please comment us below.

Leave a Comment