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

Azoruk's avatar

How many queries is too many?

I have a laravel website that lists "submissions" much like reddit. I use this example to more easily understand this problem.

When a user visits the home page, for example, he'll see 30 submissions listed.

Each submission represents a lot of information. Sure there's information from the submission itself, like the title and whatnot. But there's things like "save". For each submission, there must be a query to see if that user hasn't saved the submission, or else it would display "unsave".

Blade:

@if (!Auth::user()->hasSavedSubmission($submission))
    <a href="{{ route('save.submission', ['ID' => $submission->id, 'token' => $submission->token]) }}">Save</a>
@else
    <a href="{{ route('unsave.submission', ['ID' => $submission->id, 'token' => $submission->token]) }}">Unsave</a>                     
@endif

User Model:

 public function hasSavedSubmission(Submission $submission) {
    return (bool) $submission->savedSubmissions->where('user_id', $this->id)->count();
}   

Which then requires a query. But there isn't just hasSavedSubmission, there's a query to see if the user has upvoted/downvoted a submission, or whether or not they've subscribed to that sub.

It gets even worse on comment pages. Let's say I load a comments page with 200 comments. Well, to see if you've saved a comment or voted on a comment, that's 2 queries per comment, making it a total of 400 queries.

Is this normal? Is this good practice, or should I be optimizing this somehow to reduce queries, and how?

0 likes
3 replies
Mo7sin's avatar

I believe 400 queries are too much!

The key here is how do you check to see if the user has voted or submitted or whatever he did on the current model? I see you use savedSubmissions relationship, why don't you eager load it?

Please or to participate in this conversation.