Home » PHP » Laravel: Eloquent Sort By Relation

About Francis Adu Gyamfi

Francis Adu Gyamfi

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)
                    ->with('program')
                    ->orderBy('long_name', 'asc') // throws error
                    ->paginate($limit);

    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)
                    ->select('schedule_programs.*')
                    ->join('programs', 'programs.id', '=', 'schedule_programs.program_id')
                    ->orderBy('long_name', 'asc')
                    ->with('program') // gets the related data
                    ->paginate($limit);

    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.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
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 agree to the Terms and Privacy Policy

Leave a Reply

avatar

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

  Subscribe  
Notify of