DEV Community

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

How To Export CSV File In Laravel Example

In this article, we will see how to export CSV files in laravel. Export CSV file in laravel is the most common function and many times we are using this function using plugins or readymade functions. Also in this example, we use fopen() and fputcsv() function. The fputcsv() function formats a line as CSV and writes it to an open file. The fopen() function opens a file or URL. Here, I will give you an example export CSV files in laravel 8 without using any type of plugin in laravel.

So, let's see how to export the csv files in laravel 8, export csv file in laravel 8, download csv file in laravel, create csv file in laravel 8, laravel 8 export to csv, laravel 8 export data to csv, fputcsv in php, export csv file in php, php export csv file, export to csv php.

Step 1 : Add Route

In this step, add a route in the web.php file.

Route::get('/export-csv', 'ExampleController@exportCSV');
Enter fullscreen mode Exit fullscreen mode

Read Also : Laravel 8 cURL HTTP Request Example


Step 2 : In Blade File

Add an export button link in your blade file from where you want to export your data.

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

Step 3 : Add Script in JS file

Now, add the below script after the body tag.

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

Read Also : How To Validate URL In PHP With Regex


Step 4 : Add Function in Controller

Now, Copy the below code and add it to your 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);
    }
Enter fullscreen mode Exit fullscreen mode

You might also like:

Top comments (0)