New way to define accessor and mutator

New way to define attribute accessors and mutators in Laravel 8.77:

1// Before, two-method approach
2public function setTitleAttribute($value)
3{
4 $this->attributes['title'] = strtolower($value);
5}
6public function getTitleAttribute($value)
7{
8 return strtoupper($value);
9}
10 
11// New approach
12protected function title(): Attribute
13{
14 return new Attribute(
15 get: fn ($value) => strtoupper($value),
16 set: fn ($value) => strtolower($value),
17}

Tip given by @Teacoders

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