← Back to all snippets
PHP

Transforming Model Attributes with Eloquent Accessors and Mutators

Learn to use Eloquent accessors to format attribute values when retrieved, and mutators to transform values before they are saved to the database.

// In User model:
public function getFullNameAttribute()
{
    return $this->first_name . ' ' . $this->last_name;
}

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

// Usage:
$user = User::find(1);
echo $user->full_name; // Accessor
$user->password = 'new_secret'; // Mutator
$user->save();
How it works: Accessors allow you to transform Eloquent attribute values when they are retrieved from the model. For example, `getFullNameAttribute` combines `first_name` and `last_name` into a `full_name` attribute. Mutators transform attribute values before they are saved to the database, like automatically hashing a password with `setPasswordAttribute`. They provide a clean way to manage data presentation and storage 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