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...
Which tool do you recommend to see queries on apis?
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