laravel order by relation code example
Example 1: laravel orderby with relation
$users = User::with(['student' => function ($q) {
$q->orderBy('id', 'desc');
}]);
Example 2: laravel query order by relation
$order = 'desc';
$users = User::join('roles', 'users.role_id', '=', 'roles.id')->orderBy('roles.label', $order)->select('users.*')->paginate(10);
Example 3: laravel belongs to order by
$school = School::with(['students' => function ($q) {
$q->orderBy('whateverField', 'asc/desc');
}])->find($schoolId);
$school = School::find($schoolId);
$school->load(['students' => function ($q) {
$q->orderBy('whateverField', 'asc/desc');
}]);
$school = School::find($schoolId);
$school->students->sortBy('whateverProperty');
$school->students->sortByDesc('whateverProperty');
$students = Student::whereHas('school', function ($q) use ($schoolId) {
$q->where('id', $schoolId);
})->orderBy('whateverField')->get();