Level 58
To export Excel in Laravel using the maatwebsite/excel package, you can follow these steps:
- Install the package using Composer:
composer require maatwebsite/excel
- Publish the configuration file:
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
- Create a new export class using the
make:exportArtisan command:
php artisan make:export UsersExport --model=User
- In the
UsersExportclass, define the data that you want to export in thequery()method:
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromQuery;
class UsersExport implements FromQuery
{
public function query()
{
return User::query();
}
}
- In your controller, create a new instance of the
UsersExportclass and use thedownload()method to generate and download the Excel file:
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
class UserController extends Controller
{
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}
}
- Finally, create a route to your controller method:
Route::get('/export', [UserController::class, 'export']);
Now you can visit /export in your browser to download the Excel file.