Bird
Raised Fist0
Laravelframework~10 mins

Accessors and mutators in Laravel - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Accessors and mutators
Model instance created
↓
Set attribute value
↓
Mutator modifies value before saving
↓
Value saved in database
↓
Get attribute value
↓
Accessor modifies value before returning
↓
Return modified value to user
This flow shows how Laravel modifies model attributes when saving and retrieving using mutators and accessors.
Execution Sample
Laravel
class User extends Model {
  public function setNameAttribute($value) {
    $this->attributes['name'] = strtolower($value);
  }
  public function getNameAttribute($value) {
    return ucfirst($value);
  }
}
$user = new User();
$user->name = 'ALICE';
echo $user->name;
This code sets a user's name with a mutator that lowercases it before saving, and an accessor that capitalizes it when retrieved.
Execution Table
StepActionInput ValueMutator OutputAccessor OutputResult
1Create User instance---User object created
2Set name attributeALICEalice-Name stored as 'alice' internally
3Get name attribute--AliceAccessor returns 'Alice'
4Echo name--AliceOutput: Alice
5End---Execution complete
💡 All steps executed; final output is 'Alice' after accessor modifies stored value.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
$user->attributes['name']nullalicealicealice
$user->name (accessor)nullN/AAliceAlice
Key Moments - 2 Insights
Why does the stored name become lowercase but the output is capitalized?
The mutator changes the input to lowercase before saving (see Step 2), and the accessor capitalizes the stored value when retrieving it (see Step 3).
What happens if you access the attribute directly without the accessor?
Accessing the raw attribute (like $user->attributes['name']) returns the lowercase value stored by the mutator, not the capitalized version.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $user->attributes['name'] after Step 2?
Aalice
BALICE
CAlice
Dnull
💡 Hint
Check the 'Mutator Output' column in Step 2 of the execution table.
At which step does the accessor modify the value before returning it?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Accessor Output' column in the execution table.
If the mutator was removed, what would be the output at Step 4?
AAlice
BALICE
Calice
Dnull
💡 Hint
Without the mutator, the original input is stored; see Step 2 mutator output for comparison.
Concept Snapshot
Laravel Accessors and Mutators:
- Mutators modify attribute values before saving to database.
- Accessors modify attribute values when retrieving.
- Define mutator: set{Attribute}Attribute($value).
- Define accessor: get{Attribute}Attribute($value).
- Helps keep data consistent and formatted.
Full Transcript
In Laravel, accessors and mutators let you change how model attributes are saved and retrieved. When you set an attribute, a mutator can change the value before it is saved in the database. When you get an attribute, an accessor can change the value before it is returned. For example, a mutator can lowercase a name before saving, and an accessor can capitalize it when you get it. This keeps data consistent and formatted nicely. The execution table shows each step: creating the user, setting the name (mutator lowercases), getting the name (accessor capitalizes), and outputting the final value. The variable tracker shows how the stored and accessed values differ. Understanding these steps helps avoid confusion about why stored and displayed values differ.

Practice

(1/5)
1. What is the main purpose of an accessor in a Laravel model?
easy
A. To modify the value when saving a model attribute
B. To validate model data before saving
C. To define relationships between models
D. To modify the value when retrieving a model attribute

Solution

  1. Step 1: Understand what an accessor does

    An accessor changes how you get or read a model attribute's value.
  2. Step 2: Differentiate from mutator

    A mutator changes the value when setting or saving, not getting.
  3. Final Answer:

    To modify the value when retrieving a model attribute -> Option D
  4. Quick Check:

    Accessor = get attribute value [OK]
Hint: Accessor modifies data on get, mutator on set [OK]
Common Mistakes:
  • Confusing accessor with mutator
  • Thinking accessor validates data
  • Mixing up relationships with accessors
2. Which of the following is the correct way to define an accessor for the name attribute in a Laravel model?
easy
A. public function name() { return $this->attributes['name']; }
B. public function setNameAttribute($value) { $this->attributes['name'] = strtolower($value); }
C. public function getNameAttribute($value) { return strtoupper($value); }
D. public function get_name() { return $this->name; }

Solution

  1. Step 1: Recall accessor naming convention

    Accessors use the format get{Attribute}Attribute with the attribute name capitalized.
  2. Step 2: Check method signature and return

    The method receives the raw value and returns the modified value.
  3. Final Answer:

    public function getNameAttribute($value) { return strtoupper($value); } -> Option C
  4. Quick Check:

    Accessor method = getNameAttribute [OK]
Hint: Accessor method name starts with get and ends with Attribute [OK]
Common Mistakes:
  • Using set prefix for accessor
  • Wrong method naming like get_name
  • Not returning a value
3. Given the following Laravel model code, what will $user->full_name output?
class User extends Model {
  public function getFullNameAttribute() {
    return $this->first_name . ' ' . $this->last_name;
  }
}
$user = new User();
$user->first_name = 'Jane';
$user->last_name = 'Doe';
echo $user->full_name;
medium
A. JaneDoe
B. Jane Doe
C. Error: Undefined property full_name
D. null

Solution

  1. Step 1: Understand the accessor method

    The method getFullNameAttribute concatenates first_name and last_name with a space.
  2. Step 2: Check assigned values and output

    first_name is 'Jane', last_name is 'Doe', so full_name returns 'Jane Doe'.
  3. Final Answer:

    Jane Doe -> Option B
  4. Quick Check:

    Accessor combines names with space [OK]
Hint: Accessor returns combined attributes as expected [OK]
Common Mistakes:
  • Forgetting space between names
  • Expecting property to exist without accessor
  • Confusing method name with property
4. Identify the error in this mutator method for the email attribute:
public function setEmailAttribute($email) {
  $this->email = strtolower($email);
}
medium
A. Should assign to $this->attributes['email'], not $this->email
B. Method name should be getEmailAttribute
C. Missing return statement
D. Mutators cannot modify email attribute

Solution

  1. Step 1: Check mutator assignment syntax

    Mutators must assign to $this->attributes['attribute'], not directly to $this->attribute.
  2. Step 2: Confirm method name and behavior

    Method name setEmailAttribute is correct; no return needed.
  3. Final Answer:

    Should assign to $this->attributes['email'], not $this->email -> Option A
  4. Quick Check:

    Mutator assigns to attributes array [OK]
Hint: Mutators assign to attributes array, not direct property [OK]
Common Mistakes:
  • Assigning directly to $this->property
  • Using accessor naming for mutator
  • Expecting return value in mutator
5. You want to store a user's phone number in a Laravel model, but always save it without spaces or dashes. Which mutator method correctly achieves this?
public function setPhoneNumberAttribute($value) {
  // Remove spaces and dashes
  $clean = str_replace([' ', '-'], '', $value);
  // Save cleaned number
  ???
}
hard
A. $this->attributes['phone_number'] = $clean;
B. $this->phone_number = $clean;
C. return $clean;
D. $this->setAttribute('phone_number', $value);

Solution

  1. Step 1: Understand mutator assignment

    Mutators must assign cleaned value to $this->attributes['phone_number'] to save properly.
  2. Step 2: Check other options

    Assigning to $this->phone_number is incorrect; returning value or calling setAttribute with original value won't clean data.
  3. Final Answer:

    $this->attributes['phone_number'] = $clean; -> Option A
  4. Quick Check:

    Mutator saves cleaned value to attributes array [OK]
Hint: Mutator cleans input and assigns to attributes array [OK]
Common Mistakes:
  • Assigning directly to property instead of attributes
  • Returning value instead of assigning
  • Using original value instead of cleaned
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard