Scaling Laravel + PostgreSQL: The 'Lateral Join' Pattern for High-Performance SaaS
The "Top N per Group" Nightmare in SaaS If you've built a multi-tenant SaaS platform, you've likely hit the "Top N per Group" wall. It usually starts with a simple requirement: "On the dashboard, s...

Source: DEV Community
The "Top N per Group" Nightmare in SaaS If you've built a multi-tenant SaaS platform, you've likely hit the "Top N per Group" wall. It usually starts with a simple requirement: "On the dashboard, show every customer along with their 3 most recent invoices." In a standard Laravel application, your first instinct is to reach for Eager Loading: $customers = Customer::with(['invoices' => function ($query) { $query->latest()->limit(3); }])->get(); The problem? Eloquent's limit() inside a with() closure doesn't work the way you expect. It applies a global limit to the entire result set, not a limit per customer. You end up with 3 invoices total for the whole collection, or you're forced to load all invoices and filter them in memory—a recipe for a memory_limit exhausted error once your data grows. The "naive" fix is often an N+1 query inside a loop, or a complex subquery that becomes unreadable and slow. But if you're using PostgreSQL, there is a far more elegant, performant, and