PHP
Define Accessors and Mutators with Laravel 9+ Attributes
Transform model attribute values on retrieval and before saving using Laravel 9+'s Attribute casting, enhancing data presentation and manipulation within your application.
// In your User model (App\Models\User.php)
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// ...
protected function name(): Attribute
{
return Attribute::make(
get: fn (string $value) => ucfirst($value), // Accessor: capitalize first letter on retrieval
set: fn (string $value) => strtolower($value), // Mutator: convert to lowercase before saving
);
}
protected function isAdmin(): Attribute
{
return Attribute::make(
get: fn () => $this->attributes['role'] === 'admin', // Virtual attribute
);
}
}
// Usage example
$user = new User();
$user->name = 'JOHN DOE'; // Mutator converts to 'john doe' before saving
$user->role = 'admin';
$user->save();
echo $user->name; // Accessor outputs 'John doe'
echo $user->isAdmin; // Outputs '1' (true)
How it works: This snippet demonstrates the modern way (Laravel 9+) to define accessors and mutators using `Illuminate\Database\Eloquent\Casts\Attribute`. Accessors (`get`) transform an attribute's value when it's retrieved from the model, while mutators (`set`) modify the value before it's saved to the database. It also shows how to create a virtual attribute (`isAdmin`) that doesn't correspond directly to a database column but is derived from other attributes.