Bird
Raised Fist0
Laravelframework~20 mins

Accessors and mutators in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Laravel Accessors & Mutators Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this accessor?
Given a Laravel model with this accessor, what will $user->full_name output?

class User extends Model {
    public function getFullNameAttribute() {
        return strtoupper($this->first_name . ' ' . $this->last_name);
    }
}

Assuming $user->first_name = 'Jane' and $user->last_name = 'Doe'.
Laravel
class User extends Model {
    public function getFullNameAttribute() {
        return strtoupper($this->first_name . ' ' . $this->last_name);
    }
}

$user = new User();
$user->first_name = 'Jane';
$user->last_name = 'Doe';
echo $user->full_name;
Ajane doe
BJane Doe
CJANE DOE
DError: Undefined property full_name
Attempts:
2 left
💡 Hint
Remember that accessors modify the value when you access the attribute.
📝 Syntax
intermediate
2:00remaining
Which mutator syntax is correct?
You want to create a mutator in a Laravel model to always store the email attribute in lowercase. Which of these method definitions is correct?
A
public function setEmail($value) {
    $this->attributes['email'] = strtolower($value);
}
B
public function setEmailAttribute($value) {
    $this->attributes['email'] = strtolower($value);
}
C
public function set_email_attribute($value) {
    $this->attributes['email'] = strtolower($value);
}
D
public function setEmailAttribute() {
    $this->attributes['email'] = strtolower($value);
}
Attempts:
2 left
💡 Hint
Mutators use camelCase with set + Attribute name + Attribute.
❓ state_output
advanced
2:00remaining
What is the value of the attribute after setting it?
Consider this Laravel model mutator:

public function setUsernameAttribute($value) {
    $this->attributes['username'] = trim(strtolower($value));
}

What will be stored in the database if you set $user->username = ' Alice123 ';?
Laravel
public function setUsernameAttribute($value) {
    $this->attributes['username'] = trim(strtolower($value));
}

$user = new User();
$user->username = '  Alice123  ';
echo $user->username;
AError: Undefined property username
B Alice123
CALICE123
Dalice123
Attempts:
2 left
💡 Hint
Mutators change the value before saving it to the attributes array.
🔧 Debug
advanced
2:00remaining
Why does this accessor not work?
This Laravel model accessor is supposed to return the user's age, but it causes an error:

public function getAgeAttribute() {
    return $this->birthdate->diffInYears(now());
}

Assuming birthdate is a date string stored in the database, why does this cause an error?
Abirthdate is a string, not a Carbon date object, so diffInYears method is undefined
BThe birthdate attribute is private and cannot be accessed
CThe now() function is not imported and causes a fatal error
DThe accessor method name is incorrect; it should be get_age_attribute
Attempts:
2 left
💡 Hint
Check the data type of birthdate when accessed in the model.
🧠 Conceptual
expert
2:00remaining
How do accessors and mutators affect JSON serialization?
In Laravel, when you convert a model to JSON using toJson(), which of the following statements about accessors and mutators is true?
AAccessors are applied and their values appear in the JSON, but mutators do not affect JSON output
BMutators modify the JSON output values, but accessors do not
CNeither accessors nor mutators affect the JSON output; only raw attributes are shown
DBoth accessors and mutators modify the JSON output values
Attempts:
2 left
💡 Hint
Think about when accessors and mutators run in the model lifecycle.

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