Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Export Excel and CSV File Tutorial

Last Updated on April 20, 2024 by

In Laravel 11, exporting CSV or Excel files means fetching data from database and download in excel or csv file.

Let’s start by creating a route and method in controller that allows users export data in CSV or Excel files using Maatwebsite\Excel:

Step 1 – Install Laravel Excel Package

Install Laravel Excel package to manage import and export process from database:

composer require maatwebsite/excel

Step 2 – Create Export Class

Run the following artisan command to create export class:

php artisan make:export UsersExport --model=User

Add the export class field in it (app/Exports/UserExport.php):

<?php

namespace App\Exports;

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

class UsersExport implements FromCollection
{
    public function collection()
    {
        return User::all();
    }
}

Step 3 – Add Routes

Add routes in web.php file to handle export requests:

use App\Http\Controllers\UserController;

Route::get('/export', [UserController::class, 'export']);

Step 4 – Create Method in Controller File

In UserController, implement methods to handle export excel and csv file.

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

class UserController extends Controller
{
    public function export()
    {
        return Excel::download(new UsersExport, 'users.xlsx');
    }
}

Step 5 – Test Application

Start the Laravel development server:

php artisan serve

Start browser and navigate to http://127.0.0.1:8000/export to export CSV or Excel files.

Leave a Comment