Laravel Eloquent: How to order results of related models?
You have a few ways of achieving this: // when eager loading $school = School::with([‘students’ => function ($q) { $q->orderBy(‘whateverField’, ‘asc/desc’); }])->find($schoolId); // when lazy loading $school = School::find($schoolId); $school->load([‘students’ => function ($q) { $q->orderBy(‘whateverField’, ‘asc/desc’); }]); // or on the collection $school = School::find($schoolId); // asc $school->students->sortBy(‘whateverProperty’); // desc $school->students->sortByDesc(‘whateverProperty’); // or querying students … Read more