Skip to content
Advertisement

Laravel – Eager loading from model relationship

On my page, I have the following pagination query:

$followingUsers = $user->followerUsers()->paginate(80); 

In the blade template, I @foreach $followingUsers as $follower

In this foreach loop, there is the following check:

@if (Auth::user()->isFollowed($follower))

This is referencing I’m using the Laravel N+1 detector, and this is telling me that this I should do the following:

You should add “with(‘AppFollower’)” to eager-load this relation.

Which of course won’t work, I can’t just write something like:

$followingUsers = $user->followerUsers()->with(‘AppFollower’)->paginate(80);

This will of course cause an error.

So how do I write this eager load? Something like…

$followingUsers = $user->followerUsers()->with(Auth::user()->isFollowed($follower))->paginate(80);  

or something. I don’t know.

Advertisement

Answer

I assume that the isFollowed a relationship on the $follower model to fetch how many followers that model has, so what the detector is telling you to do is load the relationship that is used by that method on the $followingUsers collection:

// I'm guessing the name of the relationship that is called.
$followingUsers = $user->followerUsers()->with('followers')->paginate(80);

That would fix your error however it is not the most ideal solution because presumably your users could all have a lot of followers so you are loading all followers for the 80 users in memory just to see if they include the authenticated user.
A more efficient approach would be to load the authenticated user’s followers and use that in the isFollowed. Then you don’t need to load anything because the authenticated user stays the same and Laravel can store the results of the relationship for subsequent calls.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement