Performance: Accessors and mutators
Accessors and mutators affect how data is transformed before rendering or saving, impacting server response time and client rendering speed.
protected $appends = ['full_name']; public function getFullNameAttribute() { return strtoupper($this->first_name) . ' ' . strtoupper($this->last_name); } // Use caching or eager loading when possible
public function getFullNameAttribute() {
return strtoupper($this->first_name) . ' ' . strtoupper($this->last_name);
}
// Called multiple times in a loop or view without caching| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy accessor logic called repeatedly | N/A | N/A | Increases server response time delaying paint | [X] Bad |
| Accessor with cached/computed once per instance | N/A | N/A | Faster server response, quicker paint | [OK] Good |
name attribute in a Laravel model?$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;email attribute:public function setEmailAttribute($email) {
$this->email = strtolower($email);
}public function setPhoneNumberAttribute($value) {
// Remove spaces and dashes
$clean = str_replace([' ', '-'], '', $value);
// Save cleaned number
???
}Pass the test and this pattern moves unknown