To perform AI-based forecasting, we need clean, structured time-series data. Today we’ll export our grouped sales totals to CSV format — usable for training external ML models or feeding back into GPT.
📦 Step 1: Create an export class
We’ll use Laravel Excel to export the data.
php artisan make:export SalesExport --model=Sale
In app/Exports/SalesExport.php
:
namespace App\Exports;
use App\Models\Sale;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class SalesExport implements FromCollection, WithHeadings
{
public function collection()
{
return Sale::select(
DB::raw('DATE(sale_date) as date'),
DB::raw('SUM(amount) as total')
)
->groupBy('date')
->orderBy('date')
->get();
}
public function headings(): array
{
return ['Date', 'TotalSales'];
}
}
🧪 Step 2: Add export route
In routes/web.php
:
use App\Exports\SalesExport;
use Maatwebsite\Excel\Facades\Excel;
Route::get('/sales/export', function () {
return Excel::download(new SalesExport, 'sales_data.csv');
})->name('sales.export');
📂 Step 3: Test the export
Visit:
http://localhost:8000/sales/export
A CSV will be downloaded like:
Date,TotalSales
2023-06-10,125.00
2023-06-11,190.00
...
✅ Bonus: Add export button to chart page
In resources/views/sales/index.blade.php
:
<a href="{{ route('sales.export') }}" class="inline-block bg-green-500 text-white px-4 py-2 rounded mt-4">
Export CSV for Forecasting
</a>
✅ Up next (Day 4): we’ll integrate a simple Python forecasting script using Prophet
or scikit-learn
, and connect it with Laravel via Artisan.