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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Eloquent's Attribute::make lets you define a getter and setter for one attribute in a single method.
- 2casts() declares automatic type conversion so database strings become dates, booleans, and arrays.
- 3Computed attributes can derive from other attributes and be memoized with shouldCache() to avoid repeated work.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 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
php
class TwoFactorController extends Controller { public function show(Request $request): View|RedirectResponse {
Two-factor auth challenge flow in Laravel
authentication
two-factor
middleware
Intermediate
10 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/accessors-mutators-casts-in-a-laravel-model-explained-php-24e0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.