PHP
Transform Model Attributes with Laravel Eloquent Mutators and Accessors
Easily modify or format model attributes automatically when retrieving or setting them in Laravel using Eloquent's powerful mutators and accessors for data transformation.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the user's full name (Accessor).
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function fullName(): Attribute
{
return Attribute::make(
get: fn ($value, $attributes) => strtoupper($attributes['first_name'] . ' ' . $attributes['last_name']),
);
}
/**
* Set the user's first name (Mutator).
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function firstName(): Attribute
{
return Attribute::make(
set: fn ($value) => strtolower($value),
);
}
/**
* Cast the 'options' attribute to an array.
*
* @var array<string, string>
*/
protected $casts = [
'options' => 'array',
'is_admin' => 'boolean',
'last_login_at' => 'datetime',
];
}
// Usage:
$user = new User();
$user->first_name = 'JOHN'; // Will be stored as 'john'
$user->last_name = 'Doe';
$user->options = ['theme' => 'dark', 'notifications' => true]; // Stored as JSON
$user->save();
echo $user->full_name; // Outputs 'JOHN DOE'
// Accessing casted attribute
$retrievedUser = User::find($user->id);
if ($retrievedUser->options['notifications']) {
// ...
}
How it works: Mutators allow you to transform an Eloquent attribute value when it is set on the model, while accessors transform the value when it is retrieved. This snippet shows how to define `fullName` as an accessor (combining and uppercasing first/last names) and `firstName` as a mutator (converting to lowercase before saving). It also demonstrates attribute casting, which automatically converts attributes to common data types (like `array`, `boolean`, `datetime`) when retrieved from or saved to the database.