@lindsey.homenick
To download an excel file in Laravel, you can follow these steps:
- First, make sure you have the Maatwebsite/Laravel-Excel package installed in your Laravel project. You can install it using Composer by running the following command:
1
|
composer require maatwebsite/excel
|
- Next, publish the configuration file by running the following command:
1
|
php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"
|
- Create a new controller or use an existing one to handle the file download. In the controller method, you can create an Excel file using the MaatwebsiteExcelExcel facade and return it as a download response. Here is an example:
1
2
3
4
5
6
|
use MaatwebsiteExcelFacadesExcel;
public function downloadExcelFile()
{
return Excel::download(new YourExportableClass, 'filename.xlsx');
}
|
- Create a class that implements the FromView or FromCollection interface provided by Laravel Excel. This class will define the data that will be exported to the Excel file. Here is an example using the FromCollection interface:
1
2
3
4
5
6
7
8
9
10
|
use MaatwebsiteExcelConcernsFromCollection;
use AppModelsUser;
class UsersExport implements FromCollection
{
public function collection()
{
return User::all();
}
}
|
- Finally, create a route that points to the controller method for downloading the Excel file. For example:
1
|
Route::get('/download-excel', [YourController::class, 'downloadExcelFile']);
|
Now, when you visit the specified route in your application, it will trigger the download of an Excel file containing the data returned by the FromCollection
class.