PHP
Using Accessors and Mutators in Laravel Eloquent
Learn to use Laravel Eloquent accessors to format attribute values when retrieved and mutators to modify attribute values before saving them to the database, enhancing data handling.
<?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. (Accessor)
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
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. (Mutator)
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function password(): Attribute
{
return Attribute::make(
set: fn (string $value) => bcrypt($value),
);
}
// Usage:
// $user = User::find(1);
// echo $user->full_name; // Accessor in action
// $user->password = 'newpassword'; // Mutator in action
// $user->save();
}
How it works: Accessors transform Eloquent attribute values when they are retrieved from a model instance, while mutators modify them before they are saved to the database. This allows for convenient data formatting, encryption, or other transformations directly within your model, keeping your application logic clean and consistent. Laravel 9+ uses `Attribute::make()` for a more modern approach to defining these.