Custom casts

You can create custom casts to have Laravel automatically format your Eloquent model data. Here's an example that capitalises a user's name when it is retrieved or changed.

1class CapitalizeWordsCast implements CastsAttributes
2{
3 public function get($model, string $key, $value, array $attributes)
4 {
5 return ucwords($value);
6 }
7 
8 public function set($model, string $key, $value, array $attributes)
9 {
10 return ucwords($value);
11 }
12}
13 
14class User extends Model
15{
16 protected $casts = [
17 'name' => CapitalizeWordsCast::class,
18 'email' => 'string',
19 ];
20}

Tip given by @mattkingshott

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord