php 51 lines · 8 steps

A cached settings service in Laravel

A service class that loads app settings from the database once, caches them for an hour, and invalidates on write.

Explained by highlit
1<?php
2 
3namespace App\Services;
4 
5use App\Models\Setting;
6use Illuminate\Support\Collection;
7use Illuminate\Support\Facades\Cache;
8 
9class Settings
10{
11 protected ?Collection $items = null;
12 
13 protected function load(): Collection
14 {
15 if ($this->items !== null) {
16 return $this->items;
17 }
18 
19 return $this->items = Cache::remember('settings.all', now()->addHour(), function () {
20 return Setting::query()
21 ->pluck('value', 'key')
22 ->map(fn ($value) => json_decode($value, true));
23 });
24 }
25 
26 public function get(string $key, mixed $default = null): mixed
27 {
28 return data_get($this->load(), $key, $default);
29 }
30 
31 public function all(): Collection
32 {
33 return $this->load();
34 }
35 
36 public function set(string $key, mixed $value): void
37 {
38 Setting::updateOrCreate(
39 ['key' => $key],
40 ['value' => json_encode($value)],
41 );
42 
43 $this->flush();
44 }
45 
46 public function flush(): void
47 {
48 $this->items = null;
49 Cache::forget('settings.all');
50 }
51}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Two-layer caching — an in-memory property plus a shared cache store — avoids both repeated queries and repeated deserialization within a request.
  2. 2Any write path must invalidate every cache layer, or reads will serve stale data.
  3. 3Storing settings as JSON lets a flat key/value table hold structured values transparently.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A cached settings service in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code