PHP

Transform Model Attributes with Eloquent Accessors and Mutators

Discover how to automatically format or modify model attributes when retrieving or setting them using Eloquent accessors (getters) and mutators (setters).

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

// In app/Models/User.php
class User extends Model
{
    // Accessor: Get 'full_name' attribute
    public function getFullNameAttribute(): string
    {
        return "{$this->first_name} {$this->last_name}";
    }

    // Mutator: Set 'password' attribute
    public function setPasswordAttribute(string $value):
    {
        $this->attributes['password'] = Hash::make($value);
    }
}

// Usage elsewhere, e.g., in a controller or test
$user = new App\Models\User();
$user->first_name = 'Jane';
$user->last_name = 'Doe';
$user->password = 'my-secret-password'; // Mutator automatically hashes this
$user->save();

$retrievedUser = App\Models\User::find($user->id);
echo $retrievedUser->full_name; // Accessor automatically formats this
// Output: Jane Doe
How it works: Accessors and Mutators are powerful Eloquent features that allow you to transform model attributes automatically when you retrieve or set them. An accessor (e.g., `getFullNameAttribute`) is called when you access an attribute, letting you format or compute its value. A mutator (e.g., `setPasswordAttribute`) is called before an attribute is set on the model, allowing you to clean or encrypt the data before it's saved to the database. This keeps your model logic centralized and clean.

Need help integrating this into your project?

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

Hire DigitalCodeLabs