← Back to all snippets
PHP

Creating Custom Accessors and Mutators in Eloquent

Transform Eloquent model attributes on retrieval (accessor) or before saving (mutator) to format data or perform logic automatically.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;

class User extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'password',
    ];

    /**
     * Get the user's full name (accessor).
     *
     * @return string
     */
    public function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }

    /**
     * Hash the user's password before saving (mutator).
     *
     * @param  string  $value
     * @return void
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

    // Example usage:
    // $user = User::find(1);
    // echo $user->full_name; // Automatically calls getFullNameAttribute
    // $user->password = 'new_secret_password'; // Automatically calls setPasswordAttribute
    // $user->save();
}
How it works: Accessors and Mutators allow you to transform Eloquent attribute values when they are retrieved from or saved to the database. An accessor (e.g., `getFullNameAttribute`) is called automatically when you attempt to access an attribute (e.g., `$user->full_name`), enabling dynamic formatting or concatenation. A mutator (e.g., `setPasswordAttribute`) is called when you set an attribute's value (e.g., `$user->password = '...'`), providing a convenient way to hash passwords or sanitize data before it's persisted.

Need help integrating this into your project?

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

Hire DigitalCodeLabs