Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jpeterson579's avatar

Sort eloquent query by model relationship

So I have the following query

$post = Post::where('id', $post_id)->with('ratings', 'ratings.user', 'ratings.like_votes')->firstOrFail();

How do I sort ratings by ratings with the most like_votes?

0 likes
2 replies
meeshka's avatar

@jpeterson579 You could add a condition like below:

$post = Post::where('id', $post_id)->with(['ratings', 'ratings.user', 'ratings.like_votes' => function
($query) {
    $query->orderBy('your_field', 'desc');
}])->firstOrFail();

Check Constraining Eager Loads

2 likes
jpeterson579's avatar

@meeshka Hmm, I think this would work but are you ordering the ratings.like_votes here?

To order the ratings by how many like_votes it has wouldn't it be something like

$post = Post::where('id', $post_id)->with(['ratings' => function ($query) 
{
    $query->orderBy($query.like_votes->count(), 'desc');
}, 
'ratings.user', 'ratings.like_votes'])->firstOrFail();
1 like

Please or to participate in this conversation.