1$users = User::with(['student' => function ($q) {
2 $q->orderBy('id', 'desc');
3 }]);
1// when eager loading
2$school = School::with(['students' => function ($q) {
3 $q->orderBy('whateverField', 'asc/desc');
4}])->find($schoolId);
5
6// when lazy loading
7$school = School::find($schoolId);
8$school->load(['students' => function ($q) {
9 $q->orderBy('whateverField', 'asc/desc');
10}]);
11
12// or on the collection
13$school = School::find($schoolId);
14// asc
15$school->students->sortBy('whateverProperty');
16// desc
17$school->students->sortByDesc('whateverProperty');
18
19
20// or querying students directly
21$students = Student::whereHas('school', function ($q) use ($schoolId) {
22 $q->where('id', $schoolId);
23})->orderBy('whateverField')->get();