In this episode, we kick off our exploration of how to efficiently count related items (like a user's articles) in Laravel apps — and why the standard approach might not be the best when your app starts to scale.
We start with the familiar: using the count
method on a collection, which most people do by calling $user->articles->count()
. It's quick and easy, but it can be wasteful — especially if you're only after the count and not the full collection of articles. We demonstrate this with a practical example: spinning up a new Laravel project, creating some fake users and articles, and then outputting the article count in a Blade view. To show what's happening under the hood, we install Laravel Debugbar to visualize memory usage and database queries.
What's happening? Well, fetching and counting related records this way means Laravel pulls all the articles into memory just to count them, resulting in extra queries and more memory use. Not ideal!
Then we introduce a better approach using withCount
. With this, Laravel asks the database for just the number of related items (articles, in this case) and attaches the count as an attribute on the user model, so you can simply output $user->articles_count
— no need to load the full collection. As a result, we see fewer queries and less memory used.
By the end of the episode, you'll really get why aggregates like withCount
are so handy, especially if you're displaying lots of counts across your app. Plus, we hint at what the rest of the series will bring: even more aggregate tricks, smarter queries, and ways to make your Laravel apps faster and cleaner!