← Back to all snippets
PHP

Laravel Eloquent Accessors and Mutators for Data Formatting

Transform model attributes on retrieval and saving using Laravel Eloquent accessors and mutators. Learn to format names, dates, or encrypt data effortlessly.

// In your App\Models\User.php

// Accessor: Automatically formats 'name' attribute when accessed
public function getNameAttribute($value)
{
    return ucfirst($value); // Capitalize the first letter
}

// Mutator: Automatically formats 'password' attribute when set
public function setPasswordAttribute($value)
{
    $this->attributes['password'] = bcrypt($value); // Hash the password
}

// Accessor for a derived attribute (not directly in DB)
public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

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

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

echo $user->full_name; // Accesses derived attribute
How it works: Accessors and mutators allow you to transform Eloquent model attributes when they are retrieved (accessor) or set (mutator). Accessors are defined as `getFooAttribute($value)` and mutators as `setFooAttribute($value)`. They are useful for formatting data, encrypting/decrypting values, or creating derived attributes that don't exist directly in the database.

Need help integrating this into your project?

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

Hire DigitalCodeLabs