php 49 lines · 7 steps

Caching per-tenant settings in Laravel

A service that loads a tenant's settings once, caches them for an hour, and reads them back cheaply.

Explained by highlit
1<?php
2 
3namespace App\Services;
4 
5use App\Models\Tenant;
6use Illuminate\Contracts\Cache\Repository as Cache;
7use Illuminate\Support\Facades\DB;
8 
9class TenantSettings
10{
11 protected ?Tenant $tenant = null;
12 
13 protected array $settings = [];
14 
15 public function __construct(protected Cache $cache)
16 {
17 }
18 
19 public function warm(Tenant $tenant): void
20 {
21 $this->tenant = $tenant;
22 
23 $this->settings = $this->cache->remember(
24 "tenant:{$tenant->id}:settings",
25 now()->addHour(),
26 fn () => DB::table('tenant_settings')
27 ->where('tenant_id', $tenant->id)
28 ->pluck('value', 'key')
29 ->all(),
30 );
31 }
32 
33 public function get(string $key, mixed $default = null): mixed
34 {
35 return $this->settings[$key] ?? $default;
36 }
37 
38 public function enabled(string $feature): bool
39 {
40 return filter_var($this->get("feature.{$feature}"), FILTER_VALIDATE_BOOL);
41 }
42 
43 public function flush(): void
44 {
45 if ($this->tenant) {
46 $this->cache->forget("tenant:{$this->tenant->id}:settings");
47 }
48 }
49}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Cache remember collapses a check-then-fetch into one call while keeping the expensive query inside a closure that only runs on a miss.
  2. 2Namespacing cache keys by tenant id keeps every tenant's data isolated and individually invalidatable.
  3. 3Loading settings once into an in-memory array makes repeated lookups free for the rest of the request.

Related explainers

Share this explainer

Here's the card — post it anywhere.

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