PHP

Customizing Eloquent Model Attributes with Accessors and Mutators

Learn to use accessors to format or modify Eloquent model attributes when retrieved, and mutators to transform values before they are saved to the database.

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

// App/Models/User.php
class User extends Model
{
    protected $fillable = ['first_name', 'last_name', 'email', 'password', 'role_id'];

    // Accessor: Automatically formats 'full_name' when accessed
    public function getFullNameAttribute($value)
    {
        return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
    }

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

    // Accessor: Defines a virtual attribute 'is_admin'
    public function getIsAdminAttribute()
    {
        return $this->role_id === 1; // Assuming role_id 1 is admin
    }
}

// Usage:
$user = User::find(1);
echo "User full name: " . $user->full_name . "
"; // Calls getFullNameAttribute()

$newUser = new User();
$newUser->first_name = 'Jane';
$newUser->last_name = 'Doe';
$newUser->email = '[email protected]';
$newUser->password = 'secret123'; // Calls setPasswordAttribute() for hashing
$newUser->role_id = 1;
$newUser->save();

if ($user->is_admin) { // Calls getIsAdminAttribute()
    echo "User is an administrator.
";
}
How it works: Accessors and mutators allow you to transform Eloquent model attributes when they are retrieved or set. An accessor (e.g., `getFullNameAttribute` or `getIsAdminAttribute`) modifies an attribute's value after it's retrieved from the database or creates a new virtual attribute, providing a formatted or derived value. A mutator (e.g., `setPasswordAttribute`) transforms the attribute's value before it's saved to the database, ideal for hashing passwords or cleaning data. They are powerful for centralizing data manipulation logic within your models.

Need help integrating this into your project?

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

Hire DigitalCodeLabs