How to Export Data to Excel in Laravel (Step by Step Guide)
Exporting data in Excel is one of the most common requirements in Laravel applications, especially for reports, user data, or product listings. In this guide, we will learn how to export data from a database to Excel using the Laravel Excel package.
Step 1: Install Laravel Excel Package
First, install the maatwebsite/excel package using Composer.
composer require maatwebsite/excel
Step 2: Configure the Package
After installation, the package will auto-register. If needed, you can publish the config file:
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
Step 3: Create an Export Class
Use the artisan command to create an export class. For example, to export users:
php artisan make:export UsersExport --model=User
This will generate a file at app/Exports/UsersExport.php. Update it as follows:
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
public function collection()
{
return User::all();
}
}
Step 4: Create a Controller Method
In your controller, use the Excel facade to handle the download.
namespace App\Http\Controllers;
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
class UserController extends Controller
{
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}
}
Step 5: Add a Route
Define a route in routes/web.php for exporting the Excel file.
Route::get('/export-users', [UserController::class, 'export']);
Step 6: Create a Button in Blade
Finally, add a button or link in your Blade template to trigger the export.
<a href="{{ url('/export-users') }}" class="btn btn-success">Export Users to Excel</a>
Conclusion
That’s it! 🎉 You have successfully implemented Excel export functionality in Laravel. By following these steps, you can easily export any database data like users, products, or reports into Excel files for download.