Every ERP or CRM has a customer list that people open fifty times a day. Name, number of orders, open balance, last order date. It looks like the simplest screen in the app.
Then the customer table grows to a few thousand rows, someone asks to sort by open balance, and the page that used to load instantly now takes four seconds. You open the query log and see the classic pattern: one query for the page of customers, then three more queries for every customer on that page.
This post is about fixing that screen properly with tools Eloquent already gives you: withCount , withSum , subquery selects, and subquery ordering. Everything below is from the Laravel 13 docs, and I ran the examples against a real database before writing about them.
The problem: aggregates computed in PHP
Here is the version most of us wrote at some point:
<?…