0
0
LaravelHow-ToBeginner · 4 min read

How to Use Mutators in Eloquent Models in Laravel

In Laravel Eloquent, use setAttributeNameAttribute methods as mutators to automatically modify attribute values when setting them. Define a public method in your model with the pattern set{AttributeName}Attribute($value) to customize how data is saved.
📐

Syntax

A mutator in Eloquent is a method in your model that modifies an attribute's value before saving it to the database. The method name must follow this pattern:

  • set{AttributeName}Attribute($value) where {AttributeName} is the camel-cased name of the attribute.
  • The method receives the value being set and modifies it before storing.
php
public function setAttributeNameAttribute($value)
{
    $this->attributes['attribute_name'] = $value;
}
💻

Example

This example shows a User model with a mutator that automatically hashes the password when it is set.

php
<?php

namespace App\Models;

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

class User extends Model
{
    // Mutator to hash password before saving
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }
}

// Usage example
$user = new User();
$user->password = 'secret123';
// The password is automatically hashed before saving
$user->save();
Output
The password attribute is saved as a hashed string in the database instead of plain text.
⚠️

Common Pitfalls

  • Not following the exact method naming pattern set{AttributeName}Attribute will prevent the mutator from working.
  • Forgetting to assign the modified value to $this->attributes['attribute_name'] means the attribute won't be changed.
  • Using the wrong attribute key (must be snake_case) inside $this->attributes can cause bugs.
  • Mutators only affect setting attributes, not getting them; use accessors for that.
php
<?php
// Wrong mutator (wrong method name)
public function setpasswordAttribute($value) // should be setPasswordAttribute
{
    $this->attributes['password'] = bcrypt($value);
}

// Correct mutator
public function setPasswordAttribute($value)
{
    $this->attributes['password'] = bcrypt($value);
}
📊

Quick Reference

  • Mutator method name: set{AttributeName}Attribute
  • Use camel case for method name, snake case for attribute key
  • Assign modified value to $this->attributes['attribute_name']
  • Mutators run automatically when setting model attributes

Key Takeaways

Define mutators with the method name pattern set{AttributeName}Attribute to modify attribute values on set.
Always assign the modified value to $this->attributes['attribute_name'] inside the mutator.
Use camel case for the method name and snake case for the attribute key inside $this->attributes.
Mutators only affect setting attributes; use accessors to modify values when getting attributes.
Mutators help keep your data consistent and secure, like hashing passwords automatically.