TechnicalEloquent performance

Eloquent performanceLesson 6 of 28

Optimize Circular Relationships

If the parent is already loaded, give it to the children with setRelation().

2 min readIntermediateLesson

Eloquent performance06

The problem

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 fix

The feature is already in memory. Hand it to each comment directly instead of letting them query for it.

✕ Instead of this

$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;
}

✓ Do this

$feature->load('comments.user');
$feature->comments->each->setRelation('feature', $feature);

The benefit

85 queries become 3, with no duplicate models. The same isAuthor() code now runs on data already in memory.

Results

Queries

853

96% lower

Comment models

1,72241

98% lower

1 feature, no duplicates

Why it works

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.

Watch out

  • Eager loading comments.feature.comments gets to 5 queries, but loads duplicates (82 comments, 2 features). That's reloading data you already have.

Frame from lesson 6

FeaturesController::show() loads comments.user, then $feature->comments->each->setRelation(...) (being typed here) points every comment back at the feature already in memory.

Frame from lesson 6

Result: the Author badge shows only on Neil, and the Models tab shows 19 users, 41 comments and 1 feature, with no duplicates.

Key takeaway

If the parent is already loaded, give it to the children with setRelation().

Check yourself

Does setRelation() run a query?

Reveal answer

✓ Answer

No. It only sets the relation's value on the model in memory.