How to Export Files in Excel Format with Laravel Excel

Video thumbnail

Excel files remain one of the most widely used formats for sharing data. In Laravel projects, it is very common that at some point we need to export lists, generate periodic reports, or simply pull information out of the application to work with it externally. In my case, this usually happens when reports need to be delivered to clients, quick analyses need to be done, or other people need to manipulate data without entering the system.

To solve all this in a clean and efficient way, Laravel Excel is, without a doubt, the best option within the Laravel ecosystem.

In this article, I show you how to use Laravel Excel to export data to Excel step by step, without detours, focusing on the most common real-world case: exporting data from Eloquent to an Excel file.

Why use Laravel Excel to generate Excel files

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

In real projects, exporting data is not usually an "extra," but a recurring necessity: user lists, logs, posts, sales, monthly reports, etc. And this is where Laravel Excel shines, because it avoids manual solutions, repeated code, or unnecessary conversions.

Prepare the Project

For the project, we are going to use any Laravel installation you have, for example, the one we covered previously where we took the first steps with Laravel.

So simply create a new project or one you are using for testing and let's go.

Install Laravel Excel in a Laravel project

Basic project requirements

Before starting, make sure you have:

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

Installation with Composer

To install the package, we simply have to run the following composer command in our Laravel project:

$ composer require maatwebsite/excel

In modern versions of Laravel, the package is automatically registered thanks to auto-discovery, so you don't have to touch anything else to get started.

Publish configuration (optional)

Normally it is not necessary to modify the configuration, but if you want to have access to it:

Base configurations of Laravel Excel

Other than that, we don't have to do much, since like almost any package we get everything for free and we can generate Excel files very easily given a model to indicate the query we want to work with.

And now, we have to create or publish the configurations that come in the package by default:

$ php artisan vendor:publish

This will generate a configuration file that you can see in the project's config folder, which we will not address in this post as we don't need to change anything in it.

Exporting data to Excel in Laravel using Eloquent

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

Create our export class

Once our package is installed and configured, the next thing we need to do is generate a special file for this library in which we must implement a class with the Eloquent query (export file) on the model whose data we want to export; for this, 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 already provides a prepared structure.

By passing the model option, as you can imagine, it allows us to specify the model we want to make exportable, the data we are going to export via Excel, and in this way, some methods and procedures are auto-generated at the time of generating the file, which we will explain below.

Our model looks like the following:

<?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 one:

<?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);
    }
}

Use FromCollection to export records

This class, which is basically what will be generated in app/Exports, will allow us to indicate the collection, which is basically the SQL query through our Eloquent ORM; for example, if we want to get all records, we simply use the all() function:

use Maatwebsite\Excel\Facades\Excel;
 
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 any model we want to work with, which in this case is one called Post; in our export file, we indicate the Eloquent operations to specify which data we want to work with. In this case, it would be all posts, therefore we indicate an "all" in the collection method, but you can place some filter with a "where" or something similar to indicate a subset of data.

Define what data is exported (don't export everything)

Although Post::all() works, in practice we almost never want to export absolutely everything. Normally we filter data, dates, or statuses.

For example:

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

This is very common when generating real reports and not simple data dumps.

Download an Excel file from a controller in Laravel

Once the export class is created, all that's left is to use it.

Use the Excel Facade

In your controller:

use App\Exports\PostsExport;
use Maatwebsite\Excel\Facades\Excel;
public function export()
{
   return Excel::download(new PostsExport, 'posts.xlsx');
}

This method directly returns the Excel file download as an HTTP response.

Configure the route for the download

As in any Laravel flow, we define a route:

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

When accessing that URL, the Excel file downloads automatically. In many projects, this type of route ends up integrated into "Export" buttons within the administration panel.

Exporting the Excel from the controller

Now with the class generated earlier, the next thing we have to do is use it. For that, from your controller or create one as you wish just as we did in the post Creating a form and sending Post requests, we create the corresponding function and use the Excel Facade. We indicate the download function which receives two parameters: the previous class as the data source, and the file name. We obviously have to return this since it is the response that this function will return via http: the download of a file:

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

Export only a subset of data to Excel

One of the great strengths of Laravel Excel is that you can take advantage of all the power of Eloquent.

Filter data with where in Eloquent

You can apply any condition:

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

Configuring the route to export the Excel

From here on, these are routine steps for any process we want to do in Laravel, in this case, it would be generating a standard route that we covered previously:

And if we go to the route we configured earlier:

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

You will see that we automatically download an Excel file like the following:

Excel export via Laravel

In this way, we can easily generate an Excel file in Laravel; as you can see, you can apply any type of condition in the FromCollection class to avoid working with the entire data pool.

When to use FromCollection vs FromQuery

  • FromCollection: ideal for small or medium volumes.
  • FromQuery: better option if the table is large and you don't want to load everything into memory.

In projects with many records, I usually opt for FromQuery to avoid performance issues, although for simple lists, FromCollection is still sufficient.

File formats compatible with Laravel Excel

Laravel Excel supports multiple formats, among the most used:

  • XLSX (Excel)
  • CSV
  • TSV
  • ODS

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

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

XLSX and CSV cover 90% of real cases.

Best practices when working with Laravel Excel

After using Laravel Excel in several projects, there are some clear recommendations:

  • Do not export unnecessary columns
    • The less data, the better the performance and better experience for the person receiving the Excel.
  • Filter whenever you can
    • Exporting everything is usually unnecessary and not very useful.
  • Think about who will use the file
    • The Excel is not for the database, it's for people.
  • Be careful with large tables
    • If there are many records, use optimized queries or FromQuery.

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

Frequently asked questions about Laravel Excel

  • What is Laravel Excel?
    • It is a package for Laravel that allows importing and exporting Excel files, CSV, and other formats using Eloquent.
  • Is Laravel Excel free?
    • Yes, it is an open-source package maintained by Maatwebsite.
  • Can I export filtered data?
    • Yes, you can use any Eloquent query before exporting the data.
  • Does it work with Eloquent models?
    • Yes, in fact, it is one of its biggest advantages.

Conclusion: Laravel Excel as a practical solution for reports

Laravel Excel is an extremely practical tool for day-to-day work. Instead of reinventing the wheel, it allows you to export data from Eloquent to Excel in a clean, fast, and maintainable way.

In my case, it has become a recurring solution for reports, lists, and deliverables, especially when you need to get information out of the application without complications.

If you work with Laravel and at some point need to generate Excel files, Laravel Excel is the package you should be using.

Would you like me to translate another section or explain how to implement FromQuery for larger datasets?

In this post we are going to see how we can generate an Excel file using Laravel, for this we are going to use a package that will greatly facilitate this entire process.

I agree to receive announcements of interest about this Blog.

Andrés Cruz

ES En español