PHP

Format Model Attributes with Eloquent Accessors and Mutators

Transform database attribute values on retrieval and storage directly within Laravel Eloquent models using accessors and mutators for clean data presentation and custom manipulation logic.

<?php

// In your User model (app/Models/User.php)
class User extends Model
{
    // Accessor: Automatically capitalize the first name when retrieved
    public function getFirstNameAttribute($value)
    {
        return ucfirst($value);
    }

    // Mutator: Automatically hash the password before saving
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    // Accessor: Combine first and last name into a 'full_name' attribute
    public function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }

    // Mutator: Store combined name as separate first/last names
    public function setFullNameAttribute($value)
    {
        $names = explode(' ', $value);
        $this->attributes['first_name'] = $names[0] ?? null;
        $this->attributes['last_name'] = $names[1] ?? null;
    }
}

// Usage examples:

$user = User::find(1);

// Accessor in action:
echo $user->first_name; // 'John' (if stored as 'john')
echo $user->full_name; // 'John Doe'

// Mutator in action:
$user->password = 'new-secret-password'; // password will be hashed on save
$user->save();

$user->full_name = 'Jane Smith'; // will set first_name and last_name
$user->save();
How it works: Accessors and mutators in Laravel Eloquent provide a powerful way to transform model attributes when you retrieve or set them. Accessors (methods prefixed with `get` and suffixed with `Attribute`) automatically modify an attribute's value upon retrieval, useful for formatting or computing derived values. Mutators (methods prefixed with `set` and suffixed with `Attribute`) transform an attribute's value before it's saved to the database, ideal for tasks like hashing passwords or normalizing data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs