How to Export Data to Excel in Laravel with Laravel Excel (Step-by-Step)

- Andrés Cruz - ES En español

Video thumbnail

Excel files remain one of the most widely used formats for sharing and analyzing data. In Laravel projects, it is very common that at some point we need to export listings, generate periodic reports, or simply extract information from the application to work with it outside the system. In my case, this usually comes up when handing over reports to clients, performing quick analysis, or allowing other people to manipulate data without needing access to the application.

To solve all of this cleanly and efficiently, Laravel Excel is undoubtedly the best option within the Laravel ecosystem.

In this article, I will show you how to use Laravel Excel to export data to Excel step by step, straight to the point, focusing on the most common real-world scenario: exporting data from Eloquent to a downloadable Excel file directly from the browser.

Previously we saw how to use Queues and Jobs to postpone tasks in Laravel

Why use Laravel Excel to generate and export Excel files in PHP

Laravel Excel is a package developed by Maatwebsite that allows us to work with Excel files (XLSX, CSV, among others) directly from Laravel. Its main advantage is that it integrates seamlessly with Eloquent, making exporting data almost as simple as writing a query.

In real-world projects, exporting data is usually not an "extra", but a recurring necessity: user lists, logs, posts, sales, monthly reports, etc. This is where Laravel Excel shines, as it avoids manual solutions, repetitive code, or unnecessary conversions. Instead of building your own Excel generator from scratch, you have a clean abstraction layer that relies directly on Laravel collections and models.

Preparing the Project

For this tutorial, you can use any existing Laravel installation you have, for example, the one we covered previously where we took our first steps with Laravel.

So simply create a new project or use one you are using for testing, and let's get started.

Installing Laravel Excel in a Laravel project

Before starting, make sure you have:

  • PHP compatible with your Laravel version
  • Composer installed
  • A working Laravel project

To install the package, simply run the following Composer command at the root of your Laravel project:

$ composer require maatwebsite/excel

In modern versions of Laravel, the package is registered automatically thanks to auto-discovery, so you don't need to touch anything else to start using it.

Publishing the configuration (optional)

Normally, it is not necessary to modify the default configuration, but if you want access to it to adjust parameters like the writer driver or maximum memory, you can publish the configuration file with:

$ php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config

This will generate a config/excel.php file in your project. For this tutorial, we don't need to change anything in it, but it is useful to know it exists for more advanced projects.

Exporting data to Excel in Laravel using Eloquent

This is the core of the article and the most common case in real projects.

Creating the export class

Once the package is installed, the next step is to generate an export class: a special file provided by the library where we specify the Eloquent query whose data we want to export. To generate it, we use the following artisan command:

$ php artisan make:export PostsExport --model=Post

By passing the --model option, we indicate which model we are going to export. This generates a ready-to-use base structure in app/Exports/PostsExport.php.

The --model option allows specifying the model we want to make exportable. Based on it, the command auto-generates the necessary methods so the class knows where to fetch the data and in what format to return it.

For context, our Post model looks like this:

<?php

namespace App;

use App\Category;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'url_clean', 'content', 'category_id', 'posted'];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

And the Category model:

<?php

namespace App;

use App\Post;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['title', 'url_clean'];

    public function post()
    {
        return $this->hasMany(Post::class);
    }
}

Using FromCollection to export records

The class generated in app/Exports/ implements the FromCollection interface, which allows us to define the dataset to export through an Eloquent query. For example, if we want to get all records, we simply use the all() method:

namespace App\Exports;

use App\Post;
use Maatwebsite\Excel\Concerns\FromCollection;

class PostsExport implements FromCollection
{
    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        return Post::all();
    }
}

As you can see, we simply use the Post model and specify which data we want to export. Inside the collection() method, you can place any Eloquent query: an all() for all records, or any filter with where() to limit the dataset.

Defining what data to export (avoid exporting everything without filtering)

Although Post::all() works perfectly, in practice we almost never want to export absolutely all records. The standard practice is to filter by status, date range, or any other business condition.

For example, to export only published posts:

public function collection()
{
    return Post::where('posted', true)->get();
}

This is very common when generating real reports rather than simple raw data dumps. It is always better to export only what the user needs to see.

Downloading the Excel file from a controller in Laravel

Once the export class is created, all that's left is to invoke it from a controller. To do this, we import the Excel Facade and the PostsExport class, and create a method that returns the download:

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

public function export()
{
    return Excel::download(new PostsExport, 'posts.xlsx');
}

The Excel::download() method accepts two parameters: the export class as the data source, and the file name to be downloaded. It directly returns the HTTP response with the attached file, so the browser will download it automatically.

Setting up the download route

As in any Laravel flow, we need to define a route pointing to this method:

Route::get('/dashboard/excel/post-export', 'Dashboard\PostController@export')
    ->name('post.export');

Upon accessing that URL, the Excel file downloads automatically. In many projects, this type of route ends up integrated into "Export" buttons within the admin panel, providing real, visible value to the end user.

Exporting only a subset of data with where in Eloquent

One of the key strengths of Laravel Excel is that you can leverage the full power of Eloquent without restrictions. You can chain conditions in the exact same way you would in any query:

return Post::where('category_id', 3)->where('posted', true)->get();

You will see that upon accessing the configured route, an Excel file like the following will be downloaded automatically:

Excel export via Laravel Excel from a controller

In this way, we can easily generate an Excel file in Laravel. As you can see, you can apply any type of condition within the FromCollection class to avoid loading the entire dataset.

When to use FromCollection vs FromQuery?

Laravel Excel offers several interfaces depending on data volume and nature:

  • FromCollection: ideal for small to medium volumes. Loads all records into memory before generating the file.
  • FromQuery: the better option if the table is large and you don't want to load everything into memory. It processes data in chunks, significantly reducing RAM consumption.

In projects with many records, I usually opt for FromQuery to prevent performance issues, although for simple listings FromCollection is more than enough.

As for file formats, Laravel Excel supports the most common ones:

  • XLSX (Modern Excel)
  • CSV
  • TSV
  • ODS

Changing the format is as simple as changing the extension in the file name:

return Excel::download(new PostsExport, 'posts.csv');

XLSX and CSV cover 90% of real-world cases.

Best practices when exporting Excel files with Laravel

After using Laravel Excel across several projects, there are a few recommendations I always follow:

  • Do not export unnecessary columns:
    • The less data, the better performance and user experience for whoever receives the file.
  • Filter whenever you can:
    • Exporting the entire content of a table is usually unnecessary and not very useful for the end user.
  • Think about who will use the file:
    • Excel is for people, not for the database. Use clear column names in the user's language.
  • Be careful with large tables:
    • If there are many records, use FromQuery instead of FromCollection to prevent memory consumption spikes.

These small decisions make the difference between an export "that works" and one that is truly production-ready.

Frequently Asked Questions about Laravel Excel

  • What is Laravel Excel?
    • It is an open-source package for Laravel, maintained by Maatwebsite, that allows importing and exporting Excel, CSV, and other formats using Eloquent as the data source.
  • Is Laravel Excel free?
    • Yes, it is completely open-source and free. You can find it on GitHub and on Packagist.
  • Can I export filtered data?
    • Yes, you can use any Eloquent query inside the collection() method: filters with where(), relationships with with(), ordering with orderBy(), etc.
  • Does it work with Eloquent models?
    • Yes, in fact, it is one of its biggest advantages. Integration with Eloquent is native and very seamless.
  • How do I export to CSV instead of Excel with Laravel?
    • Simply change the file extension in Excel::download(): Excel::download(new PostsExport, 'posts.csv'). Laravel Excel will automatically detect the format based on the extension.

Conclusion: Laravel Excel as a practical solution for reports and exports

Laravel Excel is an extremely practical tool for day-to-day development. Instead of reinventing the wheel, it allows you to export data from Eloquent to Excel cleanly, quickly, and maintainably, using very few lines of code.

In my case, it has become a go-to solution for reports, listings, and deliverables, especially when you need to extract information outside the application hassle-free. The combination of make:export, FromCollection, and Excel::download() covers the vast majority of real-world cases without requiring extra configuration.

If you work with Laravel and ever need to generate or download Excel files, this is the package you should be using. Plain and simple.

Learn now how to debug your Laravel applications.

Learn how to export Excel files in Laravel using the Maatwebsite Laravel Excel package. A step-by-step guide covering Eloquent, FromCollection, direct downloads from the controller, and best practices. Compatible with XLSX and CSV.


Únete a la comunidad de desarrolladores que han decidido dejar de picar código y empezar a construir productos reales. Recibe mis mejores trucos de arquitectura cada semana:

I agree to receive announcements of interest about this Blog.