In this episode, we're taking a closer look at how Laravel handles aggregate queries when you're dealing with soft deleted models. If you're new to soft deletes, it's essentially a way to "hide" records—like comments—without actually removing them from the database. We walk through adding a deleted_at
column to the comments table, updating the model to use the SoftDeletes
trait, and running the migration.
We then update a view to show the total number of comments. Laravel automatically ignores soft deleted records in aggregate functions, so when you delete a comment, the count decreases as expected. Pretty handy!
But what if you want to also show how many comments have been deleted? We dive into using aggregates with custom constraints. By aliasing and tweaking our aggregate, we add a new field that specifically counts only soft deleted comments. This lets you easily build out user stats or admin views showing (for example) active and deleted comment counts side by side—all using efficient queries.
Finally, we touch on including soft deleted models in aggregates with the withTrashed
method, so you get full flexibility over your stats. Overall, you'll see how to mix and match aggregates, constraints, and soft delete behavior in Laravel to get just the results you want.