Today weโll add CSV and PDF export features so that your AI-powered forecast and insights can be easily shared with management or archived for reporting.
๐ฆ Step 1: Create ForecastExport class for CSV
php artisan make:export ForecastExport --model=ForecastResult
In app/Exports/ForecastExport.php
:
namespace App\Exports;
use App\Models\ForecastResult;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ForecastExport implements FromCollection, WithHeadings
{
public function collection()
{
return ForecastResult::select('forecast_date', 'yhat', 'yhat_lower', 'yhat_upper')->get();
}
public function headings(): array
{
return ['Forecast Date', 'Predicted Sales', 'Lower Bound', 'Upper Bound'];
}
}
๐ Step 2: Add CSV export route
In web.php
:
use App\Exports\ForecastExport;
use Maatwebsite\Excel\Facades\Excel;
Route::get('/forecast/export/csv', function () {
return Excel::download(new ForecastExport, 'forecast_report.csv');
})->name('forecast.export.csv');
๐งพ Step 3: Create Blade view for PDF
Create resources/views/forecast/pdf.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>Forecast Report</title>
<style>
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th, td { border: 1px solid #ddd; padding: 6px; text-align: center; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h2>AI-Powered 30-Day Forecast Report</h2>
<table>
<thead>
<tr>
<th>Date</th>
<th>Predicted</th>
<th>Lower</th>
<th>Upper</th>
</tr>
</thead>
<tbody>
@foreach($data as $row)
<tr>
<td>{{ $row->forecast_date }}</td>
<td>{{ number_format($row->yhat, 2) }}</td>
<td>{{ number_format($row->yhat_lower, 2) }}</td>
<td>{{ number_format($row->yhat_upper, 2) }}</td>
</tr>
@endforeach
</tbody>
</table>
</body>
</html>
๐งพ Step 4: Install and use DomPDF
composer require barryvdh/laravel-dompdf
Add route in web.php
:
Route::get('/forecast/export/pdf', function () {
$data = \App\Models\ForecastResult::orderBy('forecast_date')->get();
$pdf = \PDF::loadView('forecast.pdf', compact('data'));
return $pdf->download('forecast_report.pdf');
})->name('forecast.export.pdf');
๐ฑ Step 5: Add export buttons in Blade
In resources/views/sales/index.blade.php
:
<div class="flex gap-4 mt-4">
<a href="{{ route('forecast.export.csv') }}" class="bg-green-500 text-white px-4 py-2 rounded">Export CSV</a>
<a href="{{ route('forecast.export.pdf') }}" class="bg-red-500 text-white px-4 py-2 rounded">Download PDF</a>
</div>
โ Output:
forecast_report.csv
contains tabular forecast dataforecast_report.pdf
has a print-ready report for business use
โ Up next (Day 10): weโll wrap the project with dashboard cleanup, authentication, and final deployment prep.