HomeLARAVELWhat are accessors and mutators in Eloquent?

What are accessors and mutators in Eloquent?

In Laravel Eloquent, accessors and mutators are special methods that allow you to transform attributes when retrieving them from or saving them into the database.

They provide a clean and centralized way to handle attribute formatting or transformations without repeating logic everywhere in your code.


🔹 Accessors

  • Definition: Accessors are used to format / transform data when retrieving it from the database.
  • Naming convention: get{AttributeName}Attribute()
  • Usage: When you access a model property, Laravel will automatically call the accessor if it exists.

Example: Accessor

class User extends Model
{
    // Accessor for full name
    public function getFullNameAttribute()
    {
        return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
    }
}

Usage:

$user = User::find(1);
echo $user->full_name;   // John Doe (formatted automatically)

🔹 Mutators

  • Definition: Mutators are used to transform / format data before saving it into the database.
  • Naming convention: set{AttributeName}Attribute($value)
  • Usage: When you assign a value to a model property, Laravel will automatically call the mutator if it exists.

Example: Mutator

class User extends Model
{
    // Mutator for password
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }
}

Usage:

$user = new User;
$user->password = 'secret123';   // Will be saved as a hashed value
$user->save();

🔹 Combined Example (Accessor + Mutator)

class Product extends Model
{
    // Accessor: format price when retrieving
    public function getPriceAttribute($value)
    {
        return number_format($value / 100, 2); // convert from cents to dollars
    }

    // Mutator: store price in cents
    public function setPriceAttribute($value)
    {
        $this->attributes['price'] = $value * 100;
    }
}

Usage:

$product = new Product;

// Mutator in action
$product->price = 99.99; // stored as 9999 in DB

// Accessor in action
echo $product->price; // shows 99.99

✅ Summary

  • Accessors → modify data when retrieving (getters).
  • Mutators → modify data before saving (setters).
  • They help keep your model clean and DRY, handling attribute formatting in one place.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *