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

Azoruk's avatar

How to avoid N+1 problem when loading more results in blade?

I'm building a website that has submissions, and these submissions have comments. These comments are structured a lot like how reddit's are.

These comments have a lot of relationships (has the auth user saved/upvoted/downvoted the comment, does the comment have children, who created the comment).

So to avoid a bunch of unnecessary server queries, I eager load these relationships.

How can I fix this problem?

0 likes
9 replies
ftiersch's avatar

You can add additional levels of eager loading with the dot notation:

with(['children.children.children'])

This would load 3 levels of comments :)

Azoruk's avatar

Wait... it reduced the number of queries by a little bit. Might actually be onto something.

I think I need to somehow load the children's children AND its relationships, and then do that for every single child.

mikenewbuild's avatar

You don't need the repetition - in fact you're possibly overwriting the previous values.

Try:

$comments = Comment::with([
                    'children.children.children.children.children',
                    'owner',
                    'savedComments',
                    'votes'
                ])
                ->where('submission_id', $submission->id)
                ->whereNull('parent_id')
                ->orderBy('removed','asc')
                ->orderBy($sortBy, $direction)
                ->paginate(200);
ftiersch's avatar

Yeah, you would need the other relationships too.

What you could try is add the with() to the relationship:

function children() {
    return $this->hasMany(...)->with(['savedComments', ...]);
}

That might reduce it further but I'm not sure. Don't think I have tried that before :)

Azoruk's avatar

I've tried this too. Doesn't solve my issue, sadly.

Azoruk's avatar

I think what I'll have to do is load only the parent comments. For every child comment, I'll load them through an API call.

Azoruk's avatar

This returns ErrorException (E_NOTICE) Undefined offset: 0

Please or to participate in this conversation.