In this episode, we dig into how to apply constraints when working with Eloquent aggregates. Previously, we looked at a simple case where a user just had articles, and we counted them all regardless of status. Now, we're taking it a step further by introducing the concept of published and unpublished articles.
We start by adding a published_at
timestamp column to the articles table, making it nullable so unpublished articles won't have a value. Once that's set up, we update some articles to be published. The main issue we address is that our aggregate query counts all articles—for both published and unpublished ones. That's not what we want!
To solve this, we add a scope to our Article model to easily grab only published articles. Then, we update our aggregate query so it only counts articles where published_at
is not null. We do this first inline as a callback right in the relation count, and then refactor it to use the published scope, which makes the code look a lot cleaner.
After that, we show that you can also alias your aggregate for convenience and demonstrate that this filtering works wherever you want to constrain your aggregate queries. In the end, you have a flexible way to constrain aggregates to fit pretty much any filter condition you need.