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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Casting a JSON column to AsArrayObject gives you mutation tracking that plain array casts lack.
- 2Model-level $attributes defaults ensure a new record always has a valid structure before saving.
- 3Wrapping raw attribute access in intention-revealing methods keeps callers decoupled from storage details.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
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/storing-json-preferences-in-a-laravel-model-explained-php-279c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.