PHP

Transform Model Data with Eloquent Accessors and Mutators

Learn how to automatically format or modify attribute values when retrieving (accessors) or setting (mutators) them on Laravel Eloquent models.

// In App/Models/User.php
class User extends Model
{
    // Accessor for 'full_name'
    public function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }

    // Mutator for 'password'
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }
}

// Usage
$user = App\Models\User::find(1);
echo $user->full_name; // Accesses the virtual attribute

$user->password = 'new-secret-password'; // Mutates the 'password' attribute
$user->save();
How it works: Accessors allow you to transform Eloquent attribute values when they are retrieved from a model instance, enabling the creation of 'virtual' attributes like `full_name`. Mutators, conversely, allow you to transform attribute values when they are set on a model instance, such as automatically hashing a `password` before it's saved to the database. This mechanism ensures data consistency and simplifies data handling logic within your models.

Need help integrating this into your project?

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

Hire DigitalCodeLabs