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.
Incorrect
Section titled “Incorrect”<?php$invoices = Invoice::get();foreach ($invoices as $invoice) { $total = $invoice->lineItems->sum('amount'); // lazy query each iteration}Correct
Section titled “Correct”<?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.