Video Version of the Lesson
[Only for premium members]
[Only for premium members]
[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.
In this example, we want to display a list of users with:
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...