PHP
Custom Data Formatting with Eloquent Mutators and Accessors
Transform model attribute values on the fly in Laravel. Learn to use accessors for retrieval and mutators for storing formatted data.
// In App\Models\User.php
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// ... other model properties
/**
* Get or set the user's first name.
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function firstName(): Attribute
{
return Attribute::make(
get: fn (string $value) => ucfirst($value), // Accessor: called when attribute is retrieved
set: fn (string $value) => strtolower($value), // Mutator: called before attribute is saved
);
}
}
// Usage elsewhere
$user = User::factory()->create(['first_name' => 'john doe']);
echo $user->first_name; // Output: John doe (accessor capitalizes first letter)
$user->first_name = 'jane smith'; // Mutator converts to 'jane smith' before saving
$user->save();
$retrievedUser = User::find($user->id);
echo $retrievedUser->first_name; // Output: Jane smith
How it works: Eloquent's mutators and accessors (using the new `Attribute` class introduced in Laravel 9) allow you to transform model attribute values when they are retrieved or set. An accessor (the `get` closure) automatically formats data when you access the attribute, while a mutator (the `set` closure) transforms data before it's saved to the database. This is useful for tasks like formatting names, dates, or encrypting/decrypting sensitive information, ensuring consistent data representation across your application.