php 34 lines · 5 steps

How a Laravel command warms report caches

An Artisan command precomputes expensive report pages per region so users never trigger a cold query.

Explained by highlit
1namespace App\Console\Commands;
2 
3use App\Models\Region;
4use App\Services\ReportBuilder;
5use Illuminate\Console\Command;
6use Illuminate\Support\Facades\Cache;
7 
8class RefreshReportCache extends Command
9{
10 protected $signature = 'cache:refresh {--period=monthly}';
11 
12 protected $description = 'Warm cached report pages so users never hit a cold, slow query';
13 
14 public function handle(ReportBuilder $builder): int
15 {
16 $period = $this->option('period');
17 $regions = Region::active()->get();
18 
19 $this->withProgressBar($regions, function (Region $region) use ($builder, $period) {
20 $key = "reports:{$period}:region:{$region->id}";
21 
22 Cache::tags(['reports', "region:{$region->id}"])->put(
23 $key,
24 $builder->forRegion($region)->period($period)->generate(),
25 now()->addHours(6),
26 );
27 });
28 
29 $this->newLine();
30 $this->info("Warmed {$regions->count()} {$period} report(s).");
31 
32 return self::SUCCESS;
33 }
34}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Warming caches on a schedule shifts slow work off the request path and onto a background command.
  2. 2Cache tags let you group related entries so you can invalidate a whole set at once.
  3. 3Typehinting a service in handle lets Laravel's container inject it automatically.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a Laravel command warms report caches — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code