Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

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

Premium
2:39

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 of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…