PHP
Custom Attribute Logic with Eloquent Mutators and Accessors
Learn to use Laravel Eloquent mutators to modify attribute values before saving to the database and accessors to format data after retrieval, streamlining data handling.
// In your User model (app/Models/User.php)
class User extends Model
{
// Accessor: formats the full name when retrieved from the database
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
// Mutator: ensures email is saved in lowercase
public function setEmailAttribute($value)
{
$this->attributes['email'] = strtolower($value);
}
// Mutator: automatically hashes the password before saving
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
}
// Usage Example
$user = User::find(1);
echo $user->full_name; // Accessor automatically concatenates first and last name
$user->email = '[email protected]';
$user->save(); // Mutator ensures email is saved as '[email protected]'
$user->password = 'newpassword';
$user->save(); // Mutator automatically hashes the password
How it works: Accessors and mutators are powerful Eloquent features that allow you to transform model attributes when they are retrieved (accessors) or before they are saved to the database (mutators). Accessors are useful for formatting data (e.g., combining first and last names), while mutators ensure data integrity or perform automatic transformations like lowercasing emails or hashing passwords. They help encapsulate business logic within your models, leading to cleaner and more consistent code.