Avoid N+1 Queries in a Laravel Article List
Load authors alongside articles with eager loading and select relationship columns correctly.
You are reading a translated version.
An article list often displays the author for every row. Loading that relationship one row at a time can make query count grow with the number of articles: the N+1 pattern.
This example assumes posts.user_id references users.id. Define an author relationship on Post and eager-load it before passing records to Blade. The main query retains the foreign key needed to match each author.
Implementation example
// In App\Models\Post:
public function author(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(\App\Models\User::class, 'user_id');
}
// In the controller:
$posts = \App\Models\Post::query()
->select(['id', 'user_id', 'title'])
->with('author:id,name')
->orderByDesc('id')
->limit(20)
->get();
return view('articles.index', compact('posts'));
@foreach ($posts as $post)
<article>
<h2>{{ $post->title }}</h2>
<p>{{ $post->author?->name ?? 'Unknown author' }}</p>
</article>
@endforeach
Check the result
Compare development query logs before and after adding with. For a nonempty result, this example loads posts and authors in two main queries instead of one author query per row. Session or middleware queries may still appear separately.
Keep user_id in the Post selection and id in the User selection: relationship matching needs both. As an exercise, add withCount('comments') once a comments relationship exists, then inspect the queries again.
