PHP
Customizing Eloquent Attribute Retrieval with Accessors and Mutators
Discover how to use Laravel Eloquent accessors and mutators to automatically format attribute values when retrieved and transform them before saving to the database.
// In App\Models\User.php
use Illuminate\Database\Eloquent\Casts\Attribute;
protected function firstName(): Attribute
{
return Attribute::make(
get: fn (string $value) => ucfirst($value),
set: fn (string $value) => strtolower($value),
);
}
// Usage:
$user = App\Models\User::find(1);
$user->first_name = 'JOHN'; // Will be stored as 'john'
echo $user->first_name; // Will output 'John'
How it works: This snippet illustrates how to define an accessor and mutator for the `first_name` attribute using `Attribute::make()`. The `get` function automatically capitalizes the first letter when the attribute is accessed, while the `set` function converts the value to lowercase before it's saved to the database. This ensures consistent data formatting and storage without manual intervention.