Posts Learn Components Snippets Categories Tags Tools About
/

How To Export CSV Data From Laravel

Learn how to export CSV data from Laravel the easy way. Get to know how to export your Eloquent models to CSV file in Laravel

Created on Sep 15, 2021

2314 views

In this short snippet, you will learn how to export your eloquent models into CSV in Laravel. The benefit of exporting your data into CSV is that it can be considered as a backup and even allow you to create reports which later can be further worked on in Microsoft Excel and the likes.

Method 1: Export CSV Data Using fputcsv Function in Laravel


The first method to export CSV in Laravel is to use the "fputcsv()" function natively provided by Laravel. If you have an array of data like below, you can loop through each of the data and write each array into the CSV using the function as follows.
<?php

$data = [
  [1, 'John Doe', '[email protected]'],
  [2, 'Jane Doe', '[email protected]'],
  [3, 'Papa Doe', '[email protected]'],
];

$handle = fopen('user.csv', 'w');

collect($data)->each(fn ($row) => fputcsv($handle, $row));

fclose($handle);
The content of the CSV will be like below.
1,John Doe,[email protected]
2,Jane Doe,[email protected]
2,Papa Doe,[email protected]

Method 2: Export CSV Data Using Laravel Excel


The second method involves the use of a third-party package called Laravel Excel and this is a great package that allows you to do work on all things "CSV" files.
  • Import CSV
  • Export CSV
  • Customize and Modify CSV
  • Custom Mapping Data
  • More...
Firstly, to install the package you can run the command below.
composer require maatwebsite/excel
Once you have that installed you can export your eloquent model like below. Firstly create a new export type with the artisan command like below.
php artisan make:export UsersExport --model=User
The command above will generate the class below which will export all of the users when the code is executed.
<?php

namespace App\Exports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;

class UsersExport implements FromCollection
{
    public function collection()
    {
        return User::all();
    }
}
Now to call the method you can define a new controller and call the facade to export the data and download it to your local computer.
<?php

namespace App\Http\Controllers;

use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;

class UsersController extends Controller 
{
    public function export() 
    {
        return Excel::download(new UsersExport, 'users.csv');
    }
}
Finally, define a route that can be called from the browser to execute the controller method.
Route::get('users/export/', 'UsersController@export');
Now do visit "users/export" endpoint in your browser and you will see "users.csv" in your download folder.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How To Export CSV Data From Laravel

)