PHP
Defining Custom Eloquent Accessors and Mutators
Learn to transform model attributes automatically on retrieval (accessor) and before saving (mutator) in Laravel Eloquent for clean data handling.
// In your User model (e.g., app/Models/User.php)
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = ['first_name', 'last_name', 'email', 'password'];
// Accessor for 'full_name' attribute
protected function fullName(): Attribute
{
return Attribute::make(
get: fn ($value, $attributes) => ucfirst($attributes['first_name']) . ' ' . ucfirst($attributes['last_name']),
);
}
// Mutator for 'password' attribute (and accessor for it as well)
protected function password(): Attribute
{
return Attribute::make(
get: fn ($value) => "Encrypted Password", // This will be displayed when accessing $user->password
set: fn ($value) => bcrypt($value), // This will hash the password before saving
);
}
// Old way (pre-Laravel 9) for context, though new way is preferred
// public function getFirstNameAttribute($value) {
// return ucfirst($value);
// }
// public function setPasswordAttribute($value) {
// $this->attributes['password'] = bcrypt($value);
// }
}
// Example Usage (e.g., in a controller or route)
use App\Models\User;
$user = new User();
$user->first_name = 'john';
$user->last_name = 'doe';
$user->email = '[email protected]';
$user->password = 'secret'; // This will be automatically hashed
$user->save();
// Retrieve and use accessor
$retrievedUser = User::find($user->id);
echo "Full Name: " . $retrievedUser->full_name . "
"; // Accesses the 'fullName' accessor
echo "Stored Email: " . $retrievedUser->email . "
";
echo "Password (via accessor): " . $retrievedUser->password . "
"; // Accesses the 'password' accessor
How it works: Accessors and mutators allow you to transform Eloquent attribute values when they are retrieved from or saved to the database. Accessors (methods prefixed with `get` and suffixed with `Attribute`, or using `Attribute::make(get: ...)`) format attributes for display, while mutators (methods prefixed with `set` and suffixed with `Attribute`, or using `Attribute::make(set: ...)`) modify attributes before they are saved. This snippet demonstrates the modern Laravel 9+ `Attribute::make` syntax for both an accessor (combining first and last name) and a mutator (hashing a password).