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);
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...
composer require maatwebsite/excel
php artisan make:export UsersExport --model=User
<?php namespace App\Exports; use App\Models\User; use Maatwebsite\Excel\Concerns\FromCollection; class UsersExport implements FromCollection { public function collection() { return User::all(); } }
<?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'); } }
Route::get('users/export/', 'UsersController@export');
Leave a reply