PHP
Customize Eloquent Attributes with Accessors and Mutators
Enhance your Laravel Eloquent models by transforming attribute values on retrieval (accessor) or before saving (mutator) for improved data presentation and integrity.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
class User extends Model
{
use HasFactory;
/**
* Get the user's full name.
*/
protected function fullName(): Attribute
{
return Attribute::make(
get: fn (string $value, array $attributes) => ucfirst($attributes['first_name']) . ' ' . ucfirst($attributes['last_name']),
);
}
/**
* Set the user's password.
*/
protected function password(): Attribute
{
return Attribute::make(
set: fn (string $value) => bcrypt($value),
);
}
/**
* Get the user's email address in a readable format.
* Old style accessor for comparison
*/
public function getEmailAttribute(string $value): string
{
return strtoupper($value);
}
/**
* Set the user's email address to lowercase before saving.
* Old style mutator for comparison
*/
public function setEmailAttribute(string $value): void
{
$this->attributes['email'] = strtolower($value);
}
}
How it works: Accessors (getters) allow you to format Eloquent attributes when they are retrieved from the model. Mutators (setters) allow you to modify attributes before they are saved to the database. Laravel 9+ recommends using the `Attribute` class for defining accessors and mutators, providing a cleaner and more powerful way to manage these transformations with `get` and `set` closures. Older versions use explicit `getAttribute` and `setAttribute` methods.