Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

Ordering by a relationship in Eloquent

But should you do it?

Joel Clermont
Joel Clermont
2025-01-14

From our daily Laravel tips email. Get the next one in your inbox.

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!

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.