PHP

Customizing Model Attributes with Eloquent Accessors and Mutators

Transform model attributes on retrieval and storage in Laravel Eloquent using accessors to format data and mutators to process it before saving, ensuring data consistency.

// In App\Models\User.php (Laravel 9+ using Attribute class)
use Illuminate\Database\Eloquent\Casts\Attribute;

class User extends Model
{
    // Accessor: Automatically formats the full name when accessed
    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn (string $value, array $attributes) => ucfirst($attributes['first_name']) . ' ' . ucfirst($attributes['last_name']),
        );
    }

    // Mutator: Automatically encrypts password when set
    protected function password(): Attribute
    {
        return Attribute::make(
            set: fn (string $value) => bcrypt($value),
        );
    }

    // Accessor & Mutator for an email field (e.g., ensure lowercase and proper formatting)
    protected function email(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => strtolower($value),
            set: fn (string $value) => strtolower($value),
        );
    }
}

// Usage
$user = App\Models\User::find(1);
echo $user->full_name; // Accessor in action (e.g., "John Doe")

$user->password = 'new_secret_password'; // Mutator encrypts this automatically
$user->email = '[email protected]'; // Mutator converts to lowercase
$user->save();
How it works: Accessors and mutators allow you to transform Eloquent model attributes when you retrieve or set them. Accessors (`get` method in `Attribute::make`) modify attribute values immediately after they are retrieved from the database. Mutators (`set` method in `Attribute::make`) modify attribute values immediately before they are stored in the database. This is powerful for formatting data for display, ensuring data consistency (e.g., lowercasing emails), or performing actions like password hashing without cluttering your application logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs