PHP
Customizing Attribute Handling with Laravel Eloquent Accessors and Mutators
Transform model attributes when retrieving or saving them to the database using Eloquent accessors and mutators, perfect for formatting or encryption.
// In App\Models\User.php
class User extends Model
{
// Accessor: Automatically formats the name when retrieved
public function getFullNameAttribute()
{
return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
}
// Mutator: Automatically encrypts the password when saved
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
}
// Usage:
$user = App\Models\User::find(1);
echo $user->full_name; // Accesses the accessor
$user->password = 'new-secret-password'; // Triggers the mutator
$user->save();
How it works: Accessors allow you to modify or format an attribute when it is retrieved from the model. Mutators, on the other hand, let you transform an attribute's value before it's saved to the database. They provide a clean way to encapsulate data transformations directly within your model, such as formatting names, encrypting passwords, or serializing complex data structures, ensuring consistency and business logic application.