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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Caching the assembled payload once is cheaper than caching each expensive query separately.
- 2Namespacing cache keys by tenant id keeps multi-tenant data isolated and independently flushable.
- 3Pairing a remember-based read with an explicit forget gives you a clean cache invalidation story.
Related explainers
python
from functools import lru_cache import math
Memoizing number theory with lru_cache
memoization
number-theory
caching
Intermediate
8 steps
php
<?php final class UserRepository {
A safe PDO user repository in PHP
prepared-statements
repository-pattern
sql-injection
Intermediate
7 steps
ruby
class ReportGenerator def initialize(account, period) @account = account @period = period
Memoized report metrics in Ruby in Rails
memoization
query-composition
service-object
Intermediate
7 steps
python
import re from collections import defaultdict from pathlib import Path
Summarizing log files by date in Python
regex
parsing
aggregation
Intermediate
7 steps
php
<?php namespace App\Http\Controllers\Auth;
Rate-limited login in Laravel
authentication
rate-limiting
validation
Intermediate
9 steps
php
<?php namespace App\Http\Controllers;
Streaming a large CSV export in Laravel
streaming
csv-export
memory-efficiency
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/caching-tenant-dashboard-metrics-in-laravel-explained-php-2a9b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.