Courses

Laravel 12 Eloquent: Expert Level

N+1 Query: "Deeper" Examples - Packages and Count

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- $user->posts()->count() creates N+1 problem despite eager loading
- Third-party packages can cause hidden N+1 queries
- Use withCount() method for counts
- Always eager load package relationships properly

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

Let's examine another example of the N+1 query problem that's less obvious. This highlights why you should always use Laravel Debugbar to identify performance issues. Later in this course, I'll introduce additional tools for detecting N+1 queries.


The Scenario: Listing Users with Avatars and Post Counts

In this example, we want to display a list of users with:

  • User's name
  • User's avatar (image)
  • Count of posts each user has written

In our Controller, we have:

$users = User::with('posts')->get();

And in our Blade template:

@foreach($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td><img src="{{ $user->getFirstMediaUrl('avatars') }}" width="50"></td>
<td>{{ $user->posts()->count() }}</td>
</tr>
@endforeach

For the avatar images, we're using the spatie/laravel-medialibrary package, which provides a way to associate media files with any model. The documentation shows how to retrieve media items like this:

$user->getFirstMediaUrl('avatars');

In the database, the media is stored in a media table with polymorphic relations.

This code seems reasonable, but when we refresh the page and check Debugbar, we see 22 queries for just listing 10 users! Why so many?

We have two separate issues causing...

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