PHP

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.

Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button