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'.
{{ $product->comments->where('recommended', 'Yes')->count() }}
{{ $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.
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 :)
You should not do these operations in Blade templates - prepare the data in the controllers and only display, loop etc. in the templates
You should eager load the (relevant) comments
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.
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 sign in or create an account to participate in this conversation.