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

SamHam's avatar

Show total count and filtered count of relations

Hi,

I feel like I'm missing a trick doing something relatively straight forward in Laravel.

The app has 'Products' that hasMany 'Comments'. So I loop through products and count all comments in my blade view like so

{{ $product->comments->count() }}

OK, works great!.. But now what if I also want to add a count of all of my comments which match a certain criteria?

e.g. a count of all comments where $product->comments->recommended' is 'Yes'.

0 likes
5 replies
Mithrandir's avatar
Level 50
{{ $product->comments->where('recommended', 'Yes')->count() }}
tykus's avatar
{{ $product->comments->where('recommended', 'Yes')->count() }}

This is less efficient since it gets all of the Comment records associated with the Product and then filters before counting.

If you only need the count, then use the Query Builder comments() instead:

$recommendedComments = $product->comments()->where('recommended', 'Yes')->count();

And, try to avoid doing too much to get data in the Blade template, better to do this in the controller.

Mithrandir's avatar

True, @tykus but since he has just called $product->comments->count() the line before, the records have already been loaded.

I felt that going into efficiency would be unnecessarily expanding the scope of the question, but now that you have opened that can of worms :)

  1. You should not do these operations in Blade templates - prepare the data in the controllers and only display, loop etc. in the templates
  2. You should eager load the (relevant) comments
  3. You can add a relation in your Product class that can eager load just the count of recommended comments

But again - I think this is out of scope of this question.

SamHam's avatar

Hi @Mithrandir

Agreed that it's out of scope of the question, but you have fuelled my curiosity. It would be really cool to see an example of your third point i.e. eager loading a count of recommended comments.

Please or to participate in this conversation.