Courses

Laravel 12 Eloquent: Expert Level

What is N+1 Query: Typical Example, Debugbar and Eager Loading

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- N+1 problem creates separate query for each related record
- Laravel Debugbar helps identify duplicate queries
- Eager loading reduces queries

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

The N+1 query problem is, from my experience, the number one reason for performance issues in Laravel applications. It occurs when developers unintentionally run too many SQL queries under the hood, particularly when not properly loading relationships.


A Simple Example

Let's consider a common scenario: you want to display a table of posts, where each post belongs to an author. You want to show:

  • Post title
  • Author's name
  • Author's email

In your controller, you might write something like this:

$posts = Post::all();

Then in your Blade template:

@foreach($posts as $post)
<tr>
<td>{{ $post->title }}</td>
<td>{{ $post->user->name }}</td>
<td>{{ $post->user->email }}</td>
</tr>
@endforeach

This code looks logical, but it causes a serious performance issue. Why? Because $post->user doesn't automatically load the user data when...

The full lesson is only for Premium Members.
Want to access all 38 video+text lessons of this course? (1 h 34 min)

You also get:

  • 77 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord