Skip to content

ORM N+1 query (ARCH7079)

Key php.performance.orm-n-plus-one · Severity error · Category performance

Looping over a query result and accessing a related model on each element runs a separate query per row (N+1). Eager load the relationship upfront.

<?php
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name;
}
<?php
$posts = Post::with('author')->get();
foreach ($posts as $post) {
echo $post->author->name;
}

Eager load relationships accessed in the loop with with() to collapse them into one extra query.