php 52 lines · 7 steps

Caching tenant dashboard metrics in Laravel

A service class assembles per-tenant dashboard numbers and caches the whole payload for fifteen minutes.

Explained by highlit
1<?php
2 
3namespace App\Services;
4 
5use App\Models\Order;
6use Illuminate\Support\Facades\Cache;
7use Illuminate\Support\Facades\DB;
8 
9class DashboardMetrics
10{
11 public function summary(int $tenantId): array
12 {
13 return Cache::remember("dashboard.summary.{$tenantId}", now()->addMinutes(15), function () use ($tenantId) {
14 return [
15 'revenue' => $this->revenueByMonth($tenantId),
16 'top_products' => $this->topProducts($tenantId),
17 'pending_orders' => Order::forTenant($tenantId)->where('status', 'pending')->count(),
18 ];
19 });
20 }
21 
22 protected function revenueByMonth(int $tenantId): array
23 {
24 return Order::forTenant($tenantId)
25 ->where('status', 'paid')
26 ->where('created_at', '>=', now()->subYear())
27 ->selectRaw("DATE_FORMAT(created_at, '%Y-%m') as month, SUM(total) as revenue")
28 ->groupBy('month')
29 ->orderBy('month')
30 ->pluck('revenue', 'month')
31 ->all();
32 }
33 
34 protected function topProducts(int $tenantId): array
35 {
36 return DB::table('order_items')
37 ->join('orders', 'orders.id', '=', 'order_items.order_id')
38 ->where('orders.tenant_id', $tenantId)
39 ->where('orders.status', 'paid')
40 ->selectRaw('order_items.product_name, SUM(order_items.quantity) as sold')
41 ->groupBy('order_items.product_name')
42 ->orderByDesc('sold')
43 ->limit(5)
44 ->get()
45 ->toArray();
46 }
47 
48 public function flush(int $tenantId): void
49 {
50 Cache::forget("dashboard.summary.{$tenantId}");
51 }
52}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Caching the assembled payload once is cheaper than caching each expensive query separately.
  2. 2Namespacing cache keys by tenant id keeps multi-tenant data isolated and independently flushable.
  3. 3Pairing a remember-based read with an explicit forget gives you a clean cache invalidation story.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Caching tenant dashboard metrics in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code