Menu

Customer Lists Without N+1: withCount, withSum and Subquery Selects in Laravel
📰

Customer Lists Without N+1: withCount, withSum and Subquery Selects in Laravel

DEV Community: php·Tuğrul Yıldırım·about 14 hours ago
#cee6j6DO
#devto#dev#orders#customer#open
Reading 0:00
15s threshold

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:

<?…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.