Back to Jay Digital Insights

Eloquent ORM N+1 Query Optimization: Advanced Eager Loading and Subquery Selects

Published: Sep 15, 2026 Updated: Sep 15, 2026 Jay Digital Solutions Engineering Team
Eloquent ORM N+1 Query Optimization: Advanced Eager Loading and Subquery Selects

The Hidden Cost of Lazy Loading

Accessing relationships inside Blade loops without eager loading results in N+1 database queries: 1 query to fetch 100 items, and 100 subsequent queries to fetch each item's related data. In production, this causes crippling database connection pool exhaustion.

Advanced Solutions Beyond Simple with()

Use subquery selects and conditional eager loading to minimize memory footprint:

$products = Item::query()
    ->select(['id', 'name', 'price', 'category_id'])
    ->addSelect(['latest_review_rating' => Review::select('rating')
        ->whereColumn('item_id', 'items.id')
        ->latest()
        ->limit(1)
    ])
    ->with(['brand:id,name'])
    ->paginate(24);

Upgrade Your Team's Tech Stack with Jay Digital Solutions

We supply Kenyan organizations with warranty-backed commercial workstations, enterprise servers, and networking hardware.

Corporate & Retail BIG DEAL
%
Hardware promos
are here!
HP ELITEBOOK • DELL OPTIPLEX • LENOVO • SOPHOS

Official manufacturer warranty & ETIMS tax invoices across Kenya.