PHP
Customizing Model Attributes with Eloquent Accessors & Mutators
Enhance your Laravel Eloquent models using accessors to format attributes before retrieval and mutators to modify them before saving to the database.
// In your App\Models\User model:
// use Illuminate\Database\Eloquent\Casts\Attribute;
//
// class User extends Model
// {
// // Accessor: formats the 'first_name' attribute when accessed
// protected function firstName(): Attribute
// {
// return Attribute::make(
// get: fn (string $value) => ucfirst($value),
// );
// }
//
// // Mutator: modifies the 'password' attribute before saving
// protected function password(): Attribute
// {
// return Attribute::make(
// set: fn (string $value) => bcrypt($value),
// );
// }
//
// // Accessor & Mutator combined for a full_name attribute
// protected function fullName(): Attribute
// {
// return Attribute::make(
// get: fn () => "{$this->first_name} {$this->last_name}",
// set: fn (string $value) => [
// 'first_name' => explode(' ', $value)[0],
// 'last_name' => explode(' ', $value)[1] ?? '',
// ],
// );
// }
// }
// Usage:
$user = App\Models\User::find(1);
// Accessor in action (first_name will be capitalized automatically)
echo $user->first_name;
// Mutator in action (password will be hashed automatically on save)
$user->password = 'new-secret-password';
$user->save();
// Full Name Accessor
echo $user->full_name; // e.g., "John Doe"
// Full Name Mutator
$user->full_name = 'Jane Smith'; // Sets first_name to 'Jane', last_name to 'Smith'
$user->save();
How it works: Eloquent accessors and mutators allow you to transform model attributes when they are retrieved from or saved to the database. Accessors (via `get` methods or `Attribute::make(get: ...)`) format attributes for display, while mutators (via `set` methods or `Attribute::make(set: ...)`) modify attribute values before persistence. This provides a clean way to ensure data consistency, security (like password hashing), and presentation logic directly within your models.