Today we’ll connect Laravel with the Python forecasting script, allowing you to run sales predictions directly via a button click or Artisan command.
⚙️ Step 1: Store Python script inside Laravel
Create a folder:
mkdir -p app/AI
Move forecast_sales.py
into it:
app/AI/forecast_sales.py
Also save the CSV export as:
storage/app/sales_data.csv
You can later auto-export this via Laravel instead of downloading manually.
🧪 Step 2: Create a Laravel Artisan command
php artisan make:command RunSalesForecast
In app/Console/Commands/RunSalesForecast.php
:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class RunSalesForecast extends Command
{
protected $signature = 'forecast:run';
protected $description = 'Run the Python sales forecast script';
public function handle()
{
$this->info('Running sales forecast...');
$cmd = 'python3 ' . base_path('app/AI/forecast_sales.py');
$output = shell_exec($cmd);
if ($output === null) {
$this->error('Forecast script failed.');
} else {
$this->info('Forecast completed.');
Log::info('Forecast Output: ' . $output);
}
return 0;
}
}
🖼 Step 3: Show forecast image in Laravel
In your controller (optional):
public function forecastImage()
{
return response()->file(base_path('app/AI/forecast_plot.png'));
}
Route:
Route::get('/forecast/image', [SalesController::class, 'forecastImage'])->name('forecast.image');
🧪 Step 4: Run the forecast from Laravel
In terminal:
php artisan forecast:run
You’ll see:
Running sales forecast...
Forecast completed.
Now open:
http://localhost:8000/forecast/image
You’ll see the AI-generated 30-day forecast chart.
🧠 Bonus: Run forecast on button click (via queue or job)
In Blade:
<form method="POST" action="{{ route('forecast.run') }}">
@csrf
<button class="bg-indigo-500 text-white px-4 py-2 rounded">Run Forecast</button>
</form>
Add route/controller to dispatch Artisan::call('forecast:run')
.
✅ Up next (Day 6): we’ll save and display forecast data in Laravel, including prediction ranges and trendlines.