Last updated on March 6, 2023
You can export data to an excel file through maatwebsite/excel package in the Laravel Framework. This well-reputed package is created by Patrick Brouwers which imports and exports data to excel files. It has 52.53 million downloads at the time of writing this article which proves it is one of the best packages and the Laravel community loved it.
Before installing maatwebsite/excel package, make sure your web server meets the following requirements:
To install the maatwebsite/excel package, run the below composer command in the terminal.
composer require maatwebsite/excel
It takes a few seconds to install the package in the Laravel application. In the next step register the excel service provide, so open
config/app.php and add the below class into the providers array,
After this, the facade also needs to be added to the same file. So add the below Facade in the aliases array,
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
The next and last part of the installation is to publish the vendors. Run the below command to do it,
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Now we have completed the installation steps, next, let’s export data into an excel file.
If you install this Laravel package on a fresh application then you need some data in the users table to export. You can generate dummy data through the Laravel factory.
To export data, maatwebsite/excel package wants us to run the below command that creates a class and directory in the app folder
php artisan make:export UsersExport --model=User
The above command creates
UsersExport class with a collection method that returns all users through the eloquent all() method.
class UsersExport implements FromCollection
* @return \Illuminate\Support\Collection
public function collection()
UserController and import the excel facade and
UsersExport class. Then create
exportUsersWithExcel() method in the
UserController and use
download() method from the excel facade.
class UserController extends Controller
public function exportUsersWithExcel()
return Excel::download(new UsersExport, 'users-data.xlsx');
Next, create a route in the
routes/web.php to run
exportUsersWithExcel() method that exports and downloads users data with an excel file.
Route::get('/export-users-with-excel', [UserController::class, 'exportUsersWithExcel']);
Now let’s test it, run the below command that serves the application on the development server and provides URL to access
php artisan serve
Then open the browser and open the below URL
When you open it, it will export users’ data into an excel file and download it.
In this article, we learned how to install an excel package in a Laravel application and export data in an excel file. If you want to learn more about it, check out our Laravel page.