PHP

Customizing Eloquent Attributes with Mutators and Accessors

Learn to use Eloquent mutators to modify data before saving and accessors to format data when retrieving, enhancing model attribute handling.

// In your App\Models\User model
namespace App\Models;

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

class User extends Model
{
    /**
     * Get the user's first name.
     * Accessor and Mutator combined (Laravel 9+)
     */
    protected function firstName(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),
            set: fn (string $value) => strtolower($value),
        );
    }

    /**
     * Get the user's full name.
     * Accessor (Computed Property)
     */
    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->first_name . ' ' . $this->last_name,
        );
    }

    /**
     * Set the user's password.
     * Mutator (older syntax for clarity, but Attribute::make also works for set)
     */
    public function setPasswordAttribute(string $value)
    {
        $this->attributes['password'] = Hash::make($value);
    }
}

// Usage examples
$user = App\Models\User::find(1);

// Accessor: automatically capitalizes first name on retrieval
// e.g., if stored as "john", $user->first_name will return "John"
echo $user->first_name;

// Accessor: computed full name
// e.g., if first_name="John" and last_name="Doe", $user->full_name will return "John Doe"
echo $user->full_name;

// Mutator: automatically hashes password on assignment
$user->password = 'secret_password'; 
$user->save();
How it works: Accessors allow you to format Eloquent model attributes when you retrieve them, while mutators modify attributes before they are saved to the database. Starting with Laravel 9, you can define both `get` and `set` logic using a single `Attribute::make()` method for each attribute, making your model cleaner. Older syntax for mutators, like `setPasswordAttribute`, directly intercepts attribute assignments to perform operations like hashing passwords.

Need help integrating this into your project?

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

Hire DigitalCodeLabs