Each comment checks $this->feature->comments to show an "Author" badge. Every comment reloads the feature and all its comments: 85 queries and 1,722 comment models.
Queries
853
96% lower
Eloquent performanceLesson 6 of 28
If the parent is already loaded, give it to the children with setRelation().
2 min readIntermediateLesson
Each comment checks $this->feature->comments to show an "Author" badge. Every comment reloads the feature and all its comments: 85 queries and 1,722 comment models.
The feature is already in memory. Hand it to each comment directly instead of letting them query for it.
$feature->load('comments.user');
// Comment model
public function isAuthor()
{
// reloads the feature and all its comments, per comment
return $this->feature->comments->first()->user_id === $this->user_id;
}
$feature->load('comments.user');
$feature->comments->each->setRelation('feature', $feature);
85 queries become 3, with no duplicate models. The same isAuthor() code now runs on data already in memory.
Queries
853
96% lower
Comment models
1,72241
98% lower
1 feature, no duplicates
setRelation() fills a relationship in memory without touching the database. It's what Eloquent itself uses when it eager loads. Here you're doing it by hand.
comments.feature.comments gets to 5 queries, but loads duplicates (82 comments, 2 features). That's reloading data you already have.
FeaturesController::show() loads comments.user, then $feature->comments->each->setRelation(...) (being typed here) points every comment back at the feature already in memory.

Result: the Author badge shows only on Neil, and the Models tab shows 19 users, 41 comments and 1 feature, with no duplicates.
If the parent is already loaded, give it to the children with setRelation().
Does setRelation() run a query?
✓ Answer
No. It only sets the relation's value on the model in memory.