Using Accessors and Mutators in Laravel Eloquent Models
📖 Scenario: You are building a Laravel application to manage user profiles. You want to automatically format user names when retrieving and saving them in the database.
🎯 Goal: Create a Laravel Eloquent model with an accessor to always return the user's full name in uppercase, and a mutator to store the user's first name capitalized.
📋 What You'll Learn
Create a User model with first_name and last_name attributes
Add an accessor to get the full name in uppercase
Add a mutator to capitalize the first letter of the first name before saving
💡 Why This Matters
🌍 Real World
Accessors and mutators are used in Laravel applications to automatically format or transform data when reading from or writing to the database, such as formatting names, dates, or JSON fields.
💼 Career
Understanding accessors and mutators is essential for Laravel developers to write clean, maintainable code that handles data consistently and reduces errors.
Progress0 / 4 steps
1
Create the User model with first_name and last_name attributes
Create a Laravel Eloquent model class called User with protected properties first_name and last_name in the $fillable array.
Laravel
Hint
Remember to add protected $fillable with the exact attribute names.
2
Add an accessor for the full name in uppercase
Add a public method called getFullNameAttribute in the User model that returns the concatenation of first_name and last_name in uppercase letters.
Laravel
Hint
Accessor methods start with get, end with Attribute, and return the formatted value.
3
Add a mutator to capitalize the first letter of first_name
Add a public method called setFirstNameAttribute in the User model that sets the first_name attribute with the first letter capitalized.
Laravel
Hint
Mutator methods start with set, end with Attribute, and modify the attribute before saving.
4
Complete the User model with both accessor and mutator
Ensure the User model includes the $fillable array, the getFullNameAttribute accessor, and the setFirstNameAttribute mutator methods exactly as specified.
Laravel
Hint
Review all parts to ensure the model works as expected with accessor and mutator.
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
Step 1: Understand what an accessor does
An accessor changes how you get or read a model attribute's value.
Step 2: Differentiate from mutator
A mutator changes the value when setting or saving, not getting.
Final Answer:
To modify the value when retrieving a model attribute -> Option D
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
Step 1: Recall accessor naming convention
Accessors use the format get{Attribute}Attribute with the attribute name capitalized.
Step 2: Check method signature and return
The method receives the raw value and returns the modified value.
Final Answer:
public function getNameAttribute($value) { return strtoupper($value); } -> Option C
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
Step 1: Understand the accessor method
The method getFullNameAttribute concatenates first_name and last_name with a space.
Step 2: Check assigned values and output
first_name is 'Jane', last_name is 'Doe', so full_name returns 'Jane Doe'.
Final Answer:
Jane Doe -> Option B
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
Step 1: Check mutator assignment syntax
Mutators must assign to $this->attributes['attribute'], not directly to $this->attribute.
Step 2: Confirm method name and behavior
Method name setEmailAttribute is correct; no return needed.
Final Answer:
Should assign to $this->attributes['email'], not $this->email -> Option A
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
Step 1: Understand mutator assignment
Mutators must assign cleaned value to $this->attributes['phone_number'] to save properly.
Step 2: Check other options
Assigning to $this->phone_number is incorrect; returning value or calling setAttribute with original value won't clean data.
Final Answer:
$this->attributes['phone_number'] = $clean; -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.