PHP
Customize Data with Eloquent Accessors and Mutators
Transform model attributes automatically on retrieval (accessors) and before saving (mutators) to maintain data consistency and presentation logic in Laravel.
// In App\Models\User.php
class User extends Model
{
// Accessor: Automatically capitalize name when retrieved
public function getNameAttribute($value)
{
return ucfirst($value);
}
// Mutator: Automatically hash password before saving
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
}
// Usage
$user = App\Models\User::find(1);
echo $user->name; // Will output capitalized name
$newUser = new App\Models\User();
$newUser->name = 'jane doe';
$newUser->email = '[email protected]';
$newUser->password = 'secret'; // Password will be hashed automatically
$newUser->save();
How it works: Eloquent accessors allow you to transform model attributes when they are retrieved, while mutators allow you to transform attributes before they are saved to the database. Accessors are defined with a `get{AttributeName}Attribute` method and mutators with `set{AttributeName}Attribute`. This feature is powerful for data normalization, formatting, or encryption directly within your model.