Skip to main content

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

Read more here

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

Premium
3:42

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 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

D
danielrosiles ✓ Link copied!

Which tool do you recommend to see queries on apis?

M
Modestas ✓ Link copied!

I would recommend LaraDumps (free) or Ray (paid) option for this, it works pretty nicely.

You can look at our Overview video: https://www.youtube.com/watch?v=1c2MT2d00EE