PHP
Transforming Eloquent Attributes with Custom Accessors and Mutators
Discover how to define custom accessors and mutators in Laravel Eloquent to automatically format, encrypt, or modify attribute values when retrieving from or saving to the database.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class User extends Model
{
// ... other model properties ...
/**
* Get the user's full name.
*/
protected function fullName(): Attribute
{
return Attribute::make(
get: fn (string $value, array $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'],
);
}
/**
* Set the user's password, automatically hashing it.
*/
protected function password(): Attribute
{
return Attribute::make(
set: fn (string $value) => bcrypt($value),
);
}
/**
* Capitalize the user's name when retrieving it. (Old way, still works)
*/
public function getNameAttribute(string $value): string
{
return Str::upper($value);
}
/**
* Convert the name to lowercase before saving. (Old way, still works)
*/
public function setNameAttribute(string $value): void
{
$this->attributes['name'] = Str::lower($value);
}
}
// Example usage:
// $user = User::find(1);
// echo $user->full_name; // Uses accessor
// $user->password = 'new_secret'; // Uses mutator for hashing
// $user->name = 'John Doe'; // Uses setNameAttribute, then getNameAttribute on retrieval
// $user->save();
How it works: Accessors and Mutators allow you to transform Eloquent attribute values when they are retrieved from or saved to the database. Accessors (e.g., `getFullNameAttribute` or `fullName()` using `Attribute::make(get: ...)`) format attributes upon retrieval, while mutators (e.g., `setPasswordAttribute` or `password()` using `Attribute::make(set: ...)`) modify attributes before they are stored. This is useful for formatting, encryption, or validation logic.