In Laravel's Eloquent, you can define custom accessors and mutators to manipulate the value of an attribute before it is retrieved or saved to the database. This allows you to perform any additional logic or formatting on the attribute's value.
Here's how you can define and use custom accessors and mutators for Eloquent attributes in Laravel:
get
prefix followed by the studly-cased attribute name. For example, if your attribute is first_name
, your accessor method would be named getFirstNameAttribute
. Within this method, you can define any logic you want to apply to the attribute before returning its value. For example:public function getFirstNameAttribute($value)
{
return ucfirst($value); // Capitalize the first letter of the attribute's value
}
set
prefix followed by the studly-cased attribute name. For example, if your attribute is password
, your mutator method would be named setPasswordAttribute
. Within this method, you can define any logic you want to apply to the attribute's value before saving it to the database. For example:public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value); // Hash the password attribute value
}
$user = User::find(1);
echo $user->first_name; // Will output the first name attribute value after applying the accessor logic
$user = new User;
$user->password = 'mypassword'; // The mutator method setPasswordAttribute will be automatically called
$user->save(); // The modified attribute value will be saved to the database
By defining custom accessors and mutators, you can easily manipulate the attribute values in your Eloquent models without having to perform the logic explicitly every time you access or update them.