In this episode, we switch over to the authors page of our app, where we list all the users along with how many posts they've made. Right off the bat, everything seems fine: we're eager loading posts, query count is low, and there aren't that many authors. But when we check the debug bar, we notice the page is super slow and eating up way too much memory. What's up with that?
We dig into the Blade template and notice we're calling the count
method twice on each author's posts collection. Even with eager loading, this still means every single post is loaded into memory, just so PHP can count them. If an author has a lot of posts, that really adds up and kills performance — even more so if you're calling count
multiple times.
The fix? Instead of loading all posts and counting in PHP, we use Eloquent's withCount
to grab the post count directly from the database as an extra attribute. That way, we just get a simple integer for each author, no need to touch the massive related collections.
Once that's in place, we can ditch the old eager load, update the template to use the new posts_count
attribute, and — wow — our memory usage plummets from 160MB to 2MB, and the page loads way faster. As a bonus, we show how you can even customize the name of the count attribute if you want.
This lesson is all about why you should let your database do the heavy lifting for simple aggregates, and shows you exactly how to wire up withCount
for these super-common scenarios.