PHP
Manipulate Model Attributes On-the-Fly with Eloquent Accessors & Mutators
Discover how to automatically format or transform model attributes when retrieving (accessor) or setting (mutator) them, enhancing data consistency and presentation.
// In App\Models\User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
class User extends Model
{
// ... other model properties and methods ...
/**
* Get the user's first name.
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function firstName(): Attribute
{
return Attribute::make(
get: fn (string $value) => ucfirst($value),
set: fn (string $value) => strtolower($value),
);
}
/**
* Accessor for full_name attribute.
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function fullName(): Attribute
{
return Attribute::make(
get: fn () => "{$this->first_name} {$this->last_name}",
);
}
/**
* Mutator for password attribute (hashing before saving).
* Note: This is a simpler example; Laravel handles password hashing usually.
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function password(): Attribute
{
return Attribute::make(
set: fn (string $value) => bcrypt($value),
);
}
}
// Usage example in a Controller/Route:
$user = User::find(1);
echo $user->first_name; // Automatically capitalized (accessor)
echo $user->full_name; // Computed on the fly (accessor)
$user->first_name = 'JOHN'; // Automatically lowercased before saving (mutator)
$user->password = 'newpassword'; // Automatically hashed before saving (mutator)
$user->save();
How it works: This snippet demonstrates how to use Eloquent Accessors and Mutators to automatically transform model attributes. Accessors (`get:`) format data when retrieved (e.g., capitalizing a name), while Mutators (`set:`) modify data before it's saved to the database (e.g., lowercasing input or hashing a password). The `Attribute::make` syntax provides a modern, convenient way to define both.