Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

uniformnightly1's avatar

Eager-loading relationships in Laravel accessors?

I'd like to go back through my app and refactor bits that are noticeably slow and/or causing performance bottlenecks. The starting point for me is to address potential lazy-loading and N+1 issues.

I have the following sort of things through my app in accessors.

public function getCourseTypeLabelAttribute()
{
    return $this->courseType ? strtolower($this->courseType->name) : 'Unassigned';
}

Obviously here I'm calling course type name attribute without loading the course type in; how do I address these sorts of issues?

0 likes
6 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Any place where you use it, be sure you eager load the relation using with('courseType')

Doing it in the accessor is too late, if you load multiple items

If you only load one item, you can in theory use lazy loading

if (! $this->relationLoaded('courseType')) {
    $this->load('courseType');
}
return $this->courseType ? strtolower($this->courseType->name) : 'Unassigned';
Sinnbeck's avatar

@uniformnightly1 yeah that is best practice. I gave an example of lazy loading, but I would never recommend doing so in an accessor like this

TarikAli's avatar

Can we do this :

$this->loadMissing('courseType')
return $this->courseType ? strtolower($this->courseType->name) : 'Unassigned';
Snapey's avatar

@TarikAli no. If you wanted to change the letter case of a field in courseType then the accessor should be in that model

Please or to participate in this conversation.