logo
podcast Podcast
get help Get Unstuck

Ordering by a relationship in Eloquent

But should you do it?

Joel Clermont
Joel Clermont
2025-01-14

In our most recent podcast episode, I mentioned that you cannot order an Eloquent query by a field in a related model.

Well, that's not exactly correct. A very helpful listener wrote me and linked to this article by Jonathan Reinink showing exactly how you could do it.

To be totally transparent, even during recording, Aaron paused and asked me "Are you sure you can't do that?" and I was adamant. Oops!

And it has been in Laravel since version 6, so I can't use the excuse that it's a new feature.

I wanted to share this information to set the record straight, but as a slight consolation, I will also point out that in my case, the Eloquent orderBy approach is still not something I'd use. The subquery approach is functional, but the performance is not acceptable with tables of any significant size.

So, while it's possible, it's not always advisable.

Here to help,

Joel

P.S. You know what's even more satisfying than emailing me to tell me I'm wrong? Tell me in Slack in real-time!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.