PHP
Customizing Model Attributes with Accessors and Mutators
Enhance Eloquent model attributes by automatically formatting data on retrieval (accessors) or transformation on saving (mutators) for cleaner code.
// app/Models/User.php
class User extends Model
{
// Accessor: Automatically formats the 'name' attribute
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
// Mutator: Automatically encrypts the 'password' attribute when setting
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
// Example of a custom attribute (must be in $appends array)
protected $appends = ['full_name'];
}
// Usage Example
$user = new User();
$user->first_name = 'John';
$user->last_name = 'Doe';
$user->email = '[email protected]';
$user->password = 'secret'; // Mutator encrypts this
$user->save();
// Accessor automatically formats full_name
echo $user->full_name; // Outputs "John Doe"
// The password is now encrypted in the database
echo $user->password; // Outputs encrypted string
How it works: Accessors and Mutators in Laravel Eloquent allow you to transform model attributes when you retrieve or set them. An accessor (e.g., `getFullNameAttribute()`) automatically formats an attribute when it's accessed, providing a "virtual" attribute. A mutator (e.g., `setPasswordAttribute()`) transforms an attribute's value before it's saved to the database, often used for tasks like encryption or formatting. This keeps your application logic clean and centralizes data transformation within your models.