Skip to content

Lazy Load In Loop (ARCH7059)

Key php.orm.lazy-load-in-loop · Severity warning · Category orm

Accessing a lazily-loaded relation on each element of an iterated collection is the runtime trigger of N+1 when eager loading was omitted. Each access silently runs an extra query.

<?php
$invoices = Invoice::get();
foreach ($invoices as $invoice) {
$total = $invoice->lineItems->sum('amount'); // lazy query each iteration
}
<?php
$invoices = Invoice::with('lineItems')->get();
foreach ($invoices as $invoice) {
$total = $invoice->lineItems->sum('amount'); // preloaded
}

Preload the relation accessed in the loop with eager loading (with) on the query.