ホーム > Laravel > 【Laravel】How to Sort by a Related Column
Laravel

【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

  1. What We Will Do
  2. Conclusion

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!

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!