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

devondahon's avatar

Sort Eloquent query by sub-relationship's latest()

I'm able to sort a query by one of its relationships foos :

        return new UserResource(
            User::with([
                'foos' => function ($q) { $q->latest(); },
                'foos.bar',
            ])->find($user_id)
        );

But actually, I need to sort it by it's subrelationship bar. Knowing that a foo can only have one bar. How can I modify my code to order by foos.bar 's latest() ?

0 likes
1 reply
SilenceBringer's avatar

@devondahon you can't sort by column in eager-loaded table

To sort by column in related table you need to join it (in case of foo have just 1 bar it's easy)

            User::with([
                'foos' => function ($q) { $q->join('bar', ...)->orderBy('bar.my_column'); },
            ])->find($user_id)

Please or to participate in this conversation.