PHP
Customizing Eloquent Attributes with Accessors and Mutators
Transform model attributes when retrieving or setting them using Laravel Eloquent accessors (getters) and mutators (setters) for flexible data handling and formatting.
// In App\Models\User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute; // For Laravel 9+
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// Accessor: Format the name when retrieved
// For Laravel 8 and below: public function getNameAttribute($value) { return ucfirst($value); }
protected function name(): Attribute
{
return Attribute::make(
get: fn ($value) => ucfirst($value),
);
}
// Mutator: Hash the password when set
// For Laravel 8 and below: public function setPasswordAttribute($value) { $this->attributes['password'] = bcrypt($value); }
protected function password(): Attribute
{
return Attribute::make(
set: fn ($value) => bcrypt($value),
);
}
// Full Name (virtual attribute/accessor only)
// For Laravel 8 and below: public function getFullNameAttribute() { return "{$this->first_name} {$this->last_name}"; }
protected function fullName(): Attribute
{
return Attribute::make(
get: fn () => "{$this->first_name} {$this->last_name}",
);
}
}
// Usage:
$user = App\Models\User::find(1);
$user->first_name = 'john';
$user->last_name = 'doe';
$user->password = 'secret'; // Mutator hashes it automatically
$user->save();
echo $user->name; // 'John' (accessor applied)
echo $user->fullName; // 'John Doe' (virtual attribute)
// $user->password is hashed in the database
How it works: Accessors and mutators allow you to define custom logic for how a model's attributes are retrieved or set. Accessors (getters) transform an attribute's value when it's accessed, useful for formatting or computing values. Mutators (setters) modify an attribute's value before it's saved to the database, often used for data sanitization or hashing. In Laravel 9+, these are defined using `Attribute::make()` with `get` and `set` closures, offering a clean and expressive way to manage data transformations. For older Laravel versions, dedicated `getFooAttribute` and `setFooAttribute` methods are used.