In this episode, we dive into how to handle loading aggregate data (like counts or sums of related data) when you're using route model binding in Laravel. We kick things off by grabbing a user using route model binding and realize that, while we've got the user, their related aggregate data isn't automatically included. This can be a pain if your page needs, say, the number of posts a user has or the sum of something else.
First, we explore a straightforward (but less efficient) way: re-querying the user and eager loading the aggregates. However, this means extra queries, which isn’t ideal. To make things cleaner, we demo how you can use loadCount
or loadSum
to defer aggregate loading on an already retrieved model. This gives you the aggregates you want, just a bit later in the request lifecycle.
But what if you want to avoid those extra queries altogether? We go one step further and show you how to override the route model binding logic itself. By customizing the user lookup in your service provider, you can automatically include aggregate data every time a user is fetched via binding—cutting down your query count.
We wrap up by discussing tradeoffs: sometimes you want these aggregates every time, sometimes not. But now you’ve got options: load them later or pull them in right from the start through route binding customization. That's the magic of deferred loading of aggregates!