PHP
Transform Attributes with Eloquent Accessors & Mutators
Dynamically modify model attributes when retrieving or setting them using Laravel Eloquent accessors and mutators for clean data transformation.
// In App\Models\User.php
class User extends Authenticatable
{
// Accessor for 'full_name'
protected function fullName(): Attribute
{
return Attribute::make(
get: fn () => $this->first_name . ' ' . $this->last_name,
);
}
// Mutator for 'password' (automatically hashes)
protected function password(): Attribute
{
return Attribute::make(
set: fn ($value) => bcrypt($value),
);
}
// Accessor and Mutator for 'email' (example of combined)
protected function email(): Attribute
{
return Attribute::make(
get: fn ($value) => strtolower($value),
set: fn ($value) => strtolower($value),
);
}
}
// Usage example
$user = App\Models\User::find(1);
echo $user->full_name; // Accessor invoked
$user->password = 'newpassword'; // Mutator invoked (hashes password)
$user->email = '[email protected]'; // Mutator invoked (stores as [email protected])
$user->save();
How it works: Accessors and mutators allow you to transform Eloquent attribute values when they are retrieved from or set on a model instance. Accessors (e.g., `fullName`) let you define computed properties or format existing ones. Mutators (e.g., `password`) let you modify attribute values before they are saved to the database, like hashing passwords or standardizing email formats. Laravel 9+ uses the `Attribute` class for a more declarative syntax.