PHP

Customizing Data Retrieval and Storage with Eloquent Accessors and Mutators

Transform model attributes automatically when retrieved or saved to the database using Laravel Eloquent accessors (getters) and mutators (setters), enhancing data presentation and integrity.

// In App\Models\User.php
class User extends Model
{
    // Accessor: Automatically formats the 'name' attribute when retrieved
    protected function name(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),
        );
    }

    // Mutator: Automatically encrypts the 'password' attribute when saved
    protected function password(): Attribute
    {
        return Attribute::make(
            set: fn (string $value) => bcrypt($value),
        );
    }

    // Accessor for a derived attribute (not a direct database column)
    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn ($value, array $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'],
        );
    }

    // Old way (pre Laravel 9)
    // public function getTitleAttribute($value)
    // {
    //     return strtoupper($value);
    // }
    //
    // public function setPasswordAttribute($value)
    // {
    //     $this->attributes['password'] = bcrypt($value);
    // }
}

// Usage
$user = App\Models\User::find(1);
echo $user->name; // Will be capitalized

$user->password = 'new_secret_password'; // Will be hashed before saving
$user->save();

echo $user->fullName; // Combines first_name and last_name
How it works: Eloquent accessors and mutators allow you to transform model attributes automatically when they are retrieved from or saved to the database. Accessors (getters) modify the attribute's value upon retrieval, useful for formatting or derived values. Mutators (setters) modify the attribute's value before it's saved, commonly used for hashing passwords or sanitizing input. Laravel 9+ introduced the `Attribute` class for a more streamlined way to define both, as shown, while also demonstrating the older method for context.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs