Laravel 8 new flexible accessors and mutators

ยท 1 min read
Laravel 8 new flexible accessors and mutators

Till recently we had to follow some specific conventions to create accessors and mutators in Laravel by using the pattern get or set + attribute name in PascalCase + the word Atribute like so get{AttributeName}Attribute or set{AttributeName}Attribute.

Let's see an example:

use Illuminate\Database\Eloquent\Model;

class User extends Model
  // Old accessor
  public function getTitleAttribute($value)
  {
    return strtoupper($value);
  }

  // Old mutator
  public function setTitleAttribute($value)
  {
    $this->attributes['title'] = strtolower($value);
  }
}

As of Laravel 8.77 we can use a more compact syntax:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;

class User extends Model
  protected function title(): Attribute
  {
    return new Attribute(
      get: fn ($value) => strtoupper($value),
      set: fn ($value) => strtolower($value),
    );
  }
}

At the moment we can use both ways to cast attributes and define accessors and mutators so the old syntax is not considered a deprecated one. Cheers!!

Did you like this one?

I hope you really did...

Marios_thumb

Newsletter

Get notified about latest posts and updates once a week!!