Support the ongoing development of Laravel.io →
Database Eloquent

Hi,

I'm having a high number of SQL queries when I enable pagination in my view. I basically have courses, reviews for theses courses, and students writing them, and the problem happens when I want do display every written for a particular course.

When pagination is not enabled, I have a constant number of queries.

$course = Course::with('reviews.student')->findOrFail($id);

Makes the following SQL queries (bigger image here) queries

But when I pass $course->reviews()->paginate($nbPerPage) to my view (instead of $course->reviews), there are much more queries (and the number actually grows with the number of reviews) : (bigger image here)

queries

You can see there are lots of SQL queries, as well as duplicates. How to fix this?

Thank you very much! Christophe

Last updated 3 years ago.
0

You probably need to eager load

$course->reviews()->with('student')->paginate(10);
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.