php 50 lines · 6 steps

Accessors, mutators & casts in a Laravel model

How an Eloquent User model transforms attributes on read and write using Attribute casts.

Explained by highlit
1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Casts\Attribute;
6use Illuminate\Database\Eloquent\Model;
7use Illuminate\Support\Str;
8 
9class User extends Model
10{
11 protected $fillable = ['first_name', 'last_name', 'email'];
12 
13 protected function casts(): array
14 {
15 return [
16 'email_verified_at' => 'datetime',
17 'is_admin' => 'boolean',
18 'preferences' => 'array',
19 ];
20 }
21 
22 protected function firstName(): Attribute
23 {
24 return Attribute::make(
25 get: fn (string $value) => ucfirst($value),
26 set: fn (string $value) => strtolower($value),
27 );
28 }
29 
30 protected function fullName(): Attribute
31 {
32 return Attribute::make(
33 get: fn () => ucfirst($this->first_name) . ' ' . ucfirst($this->last_name),
34 )->shouldCache();
35 }
36 
37 protected function email(): Attribute
38 {
39 return Attribute::make(
40 set: fn (string $value) => strtolower(trim($value)),
41 );
42 }
43 
44 protected function slug(): Attribute
45 {
46 return Attribute::make(
47 get: fn () => Str::slug($this->full_name),
48 );
49 }
50}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Eloquent's Attribute::make lets you define a getter and setter for one attribute in a single method.
  2. 2casts() declares automatic type conversion so database strings become dates, booleans, and arrays.
  3. 3Computed attributes can derive from other attributes and be memoized with shouldCache() to avoid repeated work.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Accessors, mutators & casts in a Laravel model — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code