Eloquent eager load Order by
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Eloquent eager loading has become an essential tool for developers to build efficient and scalable applications using Laravel. In this article, we will focus on the problem of ordering eagerly loaded relationships by a specific column. Let's assume you have a one-to-one relationship between students and exams where each student can only take one exam and vice versa. Here is your current code for retrieving students with their respective exams in descending order based on exam results:
php
Student::with('exam')->orderBy('exam.result', 'DESC')->get()php
Student::with([
'exam' => function ($query) {
$query->orderBy('result', 'DESC');
}
])->get()
php
Student::withCount('exams')->orderBy('exam_count', 'DESC')->get()