Retrive relation on a polymorphic model I have a Game model that is "static". Containing game information and such, and users can comment on all games.

Games model

public function comments()
{
    return $this-&gt;morphMany(Comment::class, 'commentable');
}


And then I have a Comment model. This has a User relation and a Comments relation.

public function commentable()
{
    return $this-&gt;morphTo();
}

public function user()
{
    return $this-&gt;belongsTo(User::class);
}


What I want to do is to fetch the 10 games sorted by the latest comment top, be able to display who made the comment, and when.

I have this query that seems to do the job, but it makes an absurd amount of queries. Can I somehow keep the queries to a minimum?

    $games = Game::join('comments', 'games.id', '=', 'comments.commentable_id')
    -&gt;where('comments.commentable_type', Game::class)
    -&gt;latest('comments.created_at')
    -&gt;groupBy('games.id')
    -&gt;take(10)
    -&gt;withCount('comments')
    -&gt;get()-&gt;each(function($games){
        $games-&gt;comment = $games-&gt;comments()-&gt;orderBy('created_at', 'desc')-&gt;first();
        $games-&gt;user = User::find($games-&gt;comment-&gt;user_id);
        return $games;
    });
You didn't specify which version of Laravel is used, so I am going to presume it is 5.x. If that is incorrect, please notify me and update your post with such relevant information

I am not sure exactly how to reduce the queries for comments but the suggestion below should allow remove the loop of queries for the user on each game.

Eager Loading

(Nested) Eager Loading - utilizing the with() method - can be used to populate the user property for each item in the collection:

$games = Game::join('comments', 'games.id', '=', 'comments.commentable_id')
-&gt;where('comments.commentable_type', Game::class)
-&gt;latest('comments.created_at')
-&gt;groupBy('games.id')
-&gt;take(10)
-&gt;with('comment.user')
-&gt;withCount('comments')


Variable naming

The lambda/closure passed to each() accepts a parameter named $games. Isn't it actually a representation of a game? If so, $game would be more appropriate. Additionally, other developers reading the code may be confused because $games is also used for the assignment of the collection.