Laravel 7 Export CSV File Example Tutorial Step by Step

Laravel 7 Export CSV File Example tutorial step by step is today’s leading topic. Here in this article we are going to share how to exporting csv file in laravel 7 app easy way. More then times we need to export our data as a csv that’s the user or client see their process using csv.

Importing and exporting csv is very common any laravel or other admin project. Here we don’t use any library for exporting the csv. We use php function to generate the csv file easy way. So let’s start with Laravel 7 Export CSV File Example Tutorial Step by Step.

Step 1: Add Route

In first step we add the route in web.php file.

Route::get('/export-tasks', 'TaskController@exportCsv');

Step 2: In Blade File

Here in the blade file we add a export button for generating or download the csv file.

<span data-href="/export-tasks" id="export" class="btn btn-success btn-sm" onclick="exportTasks(event.target);">Export</span>

Step 3: In Js file

Here we redirect the url to controller.

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

Step 4: In your Controller

In last step we add the function to exporting csv easily.

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

Learn Also: How to Install and Use CKEditor In Laravel Example Tutorial

I hope this example help you… If any queries please comment below.

Leave a Comment