php 44 lines · 7 steps

Storing JSON preferences in a Laravel model

An Eloquent User model casts a JSON column to a mutable object and wraps it with clean accessor methods.

Explained by highlit
1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Casts\AsArrayObject;
6use Illuminate\Database\Eloquent\Model;
7 
8class User extends Model
9{
10 protected $fillable = [
11 'name',
12 'email',
13 'preferences',
14 ];
15 
16 protected function casts(): array
17 {
18 return [
19 'preferences' => AsArrayObject::class,
20 ];
21 }
22 
23 protected $attributes = [
24 'preferences' => '{"theme":"system","sidebar_collapsed":false,"density":"comfortable","locale":"en"}',
25 ];
26 
27 public function preference(string $key, mixed $default = null): mixed
28 {
29 return $this->preferences[$key] ?? $default;
30 }
31 
32 public function setPreference(string $key, mixed $value): static
33 {
34 $this->preferences[$key] = $value;
35 $this->save();
36 
37 return $this;
38 }
39 
40 public function prefersDarkMode(): bool
41 {
42 return $this->preference('theme') === 'dark';
43 }
44}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Casting a JSON column to AsArrayObject gives you mutation tracking that plain array casts lack.
  2. 2Model-level $attributes defaults ensure a new record always has a valid structure before saving.
  3. 3Wrapping raw attribute access in intention-revealing methods keeps callers decoupled from storage details.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Storing JSON preferences in a Laravel model — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code