Laravel has unique way to set and get a new or custom attribute in a model. I will explain with help of an example.
Accessors (Getters) and Mutators (Setters) in Laravel
Mutators
Mutators are used to transform model attributes. See the example below:
protected function name(): Attribute { return Attribute::make( get: fn (string $value) => strtolower($value) ); } ... $user = User::find(1); echo $user->name; //prints name in lower case
Accessors
For example you have first_name
and last_name
fields in your database table. In the result model you want a full_name
column in addition to first_name
and last_name
. This is how it is achieved:
First, define an accessor method in your User.php
model
protected function fullName(): Attribute { return Attribute::make( get: fn (mixed $value, array $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'] ); }
Then append full_name
attribute into the result model. There are three different ways to append new attributes.
- Defining
$appends
array in theUser.php
modelprotected $appends = ['full_name'];
- Calling
append
method on the resultant model.$user->append('full_name'); return $user;
- Calling
setAppends
method on the resultant model.$user->setAppends(['full_name']); return $user;
Note: Calling this method will overwrite model’s $appends array or any previous $model->append(‘full_name’) calls.
Modify or setting values before saving into database
For example you have a password field in users table. Just before saving values received from a form request you would want to hash it. This is how it can be done via attribute setter inside a model in Laravel.
public function setPasswordAttribute( $pass ) { $this->attributes['password'] = Hash::make( $pass ); }
Conclusion: Mutators, Accessors and predefined hook methods of Model can be used to transform model’s attributes or crease new custom attributes in different ways.