【Laravel】How to Sort by a Related Column
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
This article summarizes how to sort by a related column using Laravel's Eloquent.
What We Will Do
We want to display a list of users, but the order of the users should be based on information from their related records.
We will not use join.
Conclusion
$users = User::with('relation')
->get();
$users = $users->sortByDesc('relation.updated_at')
->values()
->all();Using join would certainly make it easy to handle sorting within SQL.
However, when dealing with complex queries while also using join to fetch related data, it may not always behave as expected or can become difficult to manage.
In such cases, sorting by a related column using collections provides a simple and effective solution.
I hope this helps someone!





