22
New way to define accessors and mutators in Laravel!
As you know there is a way to define accessor and mutator in laravel like below.
For example if we are in user model (App\Models\User):
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
public function setFirstNameAttribute($value)
{
$this->attribute['first_name'] = strtolower($value);
}
There is a new way to achieve this scenario But I must say Taylor Otwell actually mentioned it and it is quite useful and nice.
You can define both setter and getter in one single method like below:
public function firtName() :Attribute
{
return new Attribute (
get: fn($value, $attributes) => $attribute['first_name'],
set: fn($value) => 'first_name' => $value
);
}
and that would do it as another way to define accessors and mutators both in one attribute function. If don't want to write any of these you can simply pass a null value for get/set.
Lets see two more examples for user model to cracked it down:
public function fullName() :Attribute
{
return new Attribute(
get: fn($value, $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'],
set: function($value) {
[$firstName, $lastName] = explode(" ", $value);
return [
'first_name' => $firstName,
'last_name' => $lastName
];
}
);
}
public function password() :Attribute
{
return new Attribute(
get: null,
set: fn($value) => bcrypt($value)
);
}
That's it... any questions?
22