PHP

Customize Eloquent Attribute Interaction with Mutators and Accessors

Learn to use Eloquent accessors to format attribute values on retrieval and mutators to modify values before saving, enhancing data presentation and integrity.

// In App\Models\User.php
class User extends Model
{
    // Accessor: Format the 'name' attribute when retrieved
    public function getNameAttribute($value)
    {
        return ucfirst($value);
    }

    // Mutator: Set the 'password' attribute by hashing it before saving
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    // Mutator: Ensure email is always lowercase
    public function setEmailAttribute($value)
    {
        $this->attributes['email'] = strtolower($value);
    }

    // Casting attributes (e.g., JSON)
    protected $casts = [
        'options' => 'array',
        'is_admin' => 'boolean',
        'published_at' => 'datetime',
    ];
}

// Usage
$user = new App\Models\User();
$user->name = 'john doe'; // When retrieved, it will be 'John Doe'
$user->email = '[email protected]'; // Will be stored as '[email protected]'
$user->password = 'secret'; // Will be hashed before saving
$user->save();

// Accessing casted JSON column
$user->options = ['theme' => 'dark', 'notifications' => true];
$user->save();

echo $user->options['theme']; // Access as array
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., `getNameAttribute`) modifies a value when you access it on the model instance, while a mutator (e.g., `setPasswordAttribute`) modifies a value before it's saved to the database. This provides a clean way to format, sanitize, or hash data automatically. Attribute casting offers a simpler way for common type conversions like JSON, boolean, and datetime.

Need help integrating this into your project?

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

Hire DigitalCodeLabs