How To Export CSV File In Laravel Example
Tags: laravel, export, csv, php
Published: 2022-07-11 03:36:02

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');
```

---
 
**_[Read Also : Laravel 8 cURL HTTP Request Example](https://techsolutionstuff.com/post/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>
```

> 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>
```

--- 

**_[Read Also : How To Validate URL In PHP With Regex](https://techsolutionstuff.com/post/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);
    }
```
 
---

You might also like:

- **_[Read Also : Laravel Firebase Push Notification](https://techsolutionstuff.com/post/laravel-firebase-push-notification)_**

- **_[Read Also : Google Line Chart Example in Laravel 8](https://techsolutionstuff.com/post/google-line-chart-example-in-laravel-8)_**

- **_[Read Also : Laravel 8 Import Export CSV/EXCEL File Example](https://techsolutionstuff.com/post/laravel-8-import-export-csv-excel-file-example)_**

- **_[Read Also : Remove/Hide Columns While Export Data In Datatable](https://techsolutionstuff.com/post/remove-hide-columns-while-export-data-in-datatable)_**