Laravel: Eloquent Sort By Relation

In Laravel 5.7, we have the Eloquent ORM to help with fetching data. However, sometimes we want to sort the data by a field in a related model and still retain the nested object structure of relations.

public function getPrograms(Request $request, $id) {

    $limit = $request->limit ?? 15;

    $programs = SchedulePrograms::where('schedule_id', $id)
                    ->orderBy('long_name', 'asc') // throws error

    return Resource::collection($programs);

The above code throws an error because the field long_name is not present in the schedule_programs table but rather the programs table.

One way I have found to be able to achieve the correct sort order and still retain the nested structure is by

  1. joining to the related table and performing the order by
  2. then selecting the only fields from the parent table we are interested in
  3. and then using the with() function to pull the related models afterwards.
  4. Example below:

With those changes, the updated code now looks like the following:

public function getPrograms(Request $request, $id) {

    $limit = $request->limit ?? 15;

    $programs = SchedulePrograms::where('schedule_id', $id)
                    ->join('programs', '', '=', 'schedule_programs.program_id')
                    ->orderBy('long_name', 'asc')
                    ->with('program') // gets the related data

    return Resource::collection($programs);

Quick and simple, and the same number of queries (2) are performed against the database, although slightly more expensive because of the join operation. However, if you have good indexing in place, this should not present any significant impact to your database.

Happy trails my good people, and Merry Christmas

Published on Web Code Geeks with permission by Francis Adu Gyamfi, partner at our WCG program. See the original article here: Laravel: Eloquent Sort By Relation

Opinions expressed by Web Code Geeks contributors are their own.

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook


and many more ....


I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button