Laravel 9 Export Csv Example – Generate CSV in Laravel 9

Laravel Export CSV Example; In this tutorial you will learn how to export CSV File in laravel 9 or 8 step by step. Importing and exporting csv is very common any laravel or other admin project. More then times we need to export our data as a csv that’s the user or client see their process using csv.

Laravel export the dynamic data is needed any admin project so we have explain a easy php export csv file example with step by step. Here we don’t use any library for exporting the csv. We use php function to generate the csv file easy way.

Step 1: Add Route

In first step we need to add route in web.php file. So, open the routes/web.php file and put the below below routes on it;

<?php
  
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TaskController;
  
Route::get('/export-tasks', 'TaskController@exportCsv')->name('export-tasks');

Step 2: In Blade File

Next, we need to add a export button on our blade file for generating or download the csv file.

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

Step 3: In Js file

Here we will add a function in js file which will 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 need to add the function to handle to exporting csv file in laravel controller.

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 laravel export csv file example help you…

1 thought on “Laravel 9 Export Csv Example – Generate CSV in Laravel 9”

Leave a Comment