How to define and use custom accessors and mutators for Eloquent attributes in Laravel?

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:

  1. Define an accessor method in your Eloquent model. An accessor method should have the 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 }
  1. Define a mutator method in your Eloquent model. A mutator method should have the 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 }
  1. Now, you can access the modified attribute value using its name as a dynamic property on the model instance. For example:
$user = User::find(1); echo $user->first_name; // Will output the first name attribute value after applying the accessor logic
  1. When setting the value of an attribute, Eloquent will automatically call the corresponding mutator method for that attribute. For example:
$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.