Laravel 6 - Search Data by Date Range and Export to Excel
In Laravel 6, you can search for records by a date range and export the filtered data to Excel using the Maatwebsite Excel package.
1. Install Maatwebsite Excel Package
Run the following command to install maatwebsite/excel:
After installation, the service provider will be auto-discovered, so you don’t need to manually add it to config/app.php
.
2. Create Database Table and Model
Ensure your database credentials are properly set in .env
:
Create Migration for Orders Table
If you haven’t created the migration already, you can create it like this:
Modify database/migrations/xxxx_xx_xx_create_orders_table.php
:
Run the migration:
Create Order Model
Modify app/Order.php
:
3. Create Controller
Run the command to create a controller:
Modify app/Http/Controllers/OrderController.php
:
4. Create Export Class
Generate an export class for the Orders:
Modify app/Exports/OrdersExport.php
:
5. Create Blade View for Search Form
Create resources/views/orders/index.blade.php
:
6. Define Routes
Modify routes/web.php
:
7. Run the Application
Start Laravel development server:
Test the Application
-
Visit:
-
Select From Date and To Date, then click Search.
-
If results appear, click "Export to Excel" to download the Excel file.
8. Additional Features
-
Customize Excel Export Format
You can customize how your Excel looks by using more Maatwebsite Excel features, such as styling, multiple sheets, etc. -
Use Chunking for Large Data Sets
If you have large amounts of data, consider using chunking:
Conclusion
✅ Dynamic date search using whereBetween()
.
✅ Excel export with Maatwebsite Excel.
✅ User-friendly UI with a simple search form.