PHP

Define Eloquent Accessors and Mutators for Attribute Handling

Customize how model attributes are retrieved and set in Laravel Eloquent using accessors and mutators. Perfect for formatting data or performing transformations automatically.

// app/Models/User.php
namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // Accessor (old way for context, new way preferred)
    public function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }

    // Mutator (old way for context, new way preferred)
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    // New Laravel 9+ Accessor & Mutator (preferred method)
    protected function email(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => strtoupper($value), // Accessor: transform on retrieval
            set: fn (string $value) => strtolower($value), // Mutator: transform on saving
        );
    }

    // An accessor only (read-only attribute)
    protected function isAdmin(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->type === 'admin',
        );
    }
}

// Usage example
$user = User::find(1);

// Accessor: automatically gets full name
echo $user->full_name; // e.g., 'John Doe'

// Mutator: automatically hashes password
$user->password = 'newpassword';
$user->save();

// New accessor: email will be uppercase when accessed
echo $user->email; // e.g., '[email protected]'

// New mutator: email will be lowercase when saved
$user->email = '[email protected]';
$user->save(); // '[email protected]' is stored

// New accessor for isAdmin
if ($user->isAdmin) {
    echo "User is an admin.";
}
How it works: Accessors transform an Eloquent attribute when it is accessed (read), while mutators transform an attribute when it is set (written). This is useful for formatting data, encrypting/decrypting values, or performing calculations on the fly. Laravel 9+ introduces a new `Attribute::make` syntax, which combines both the accessor and mutator logic into a single method, providing a cleaner and more powerful way to define these transformations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs