Laravel Eloquent: How to order results of related models?

To answer the original question, the students dynamic property can also be accessed as a relationship method.

So you have this to fetch all students:

$students = $school->students;

Now as a relationship method, this is equivalent:

$students = $school->students()->get();

Given this, you can now add in some ordering:

$students = $school->students()->orderBy('students.last_name')->get();

Since eloquent will be performing a join, make sure to include the table name when referencing the column to order by.

You can also add this to your students method if you want to set a default order that $school->students will always return. Check out the documentation for hasMany() to see how this works.


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 directly
$students = Student::whereHas('school', function ($q) use ($schoolId) {
  $q->where('id', $schoolId);
})->orderBy('whateverField')->get();

you can add orderBy to your relation, so the only thing you need to change is

public function students()
{
    return $this->hasMany('Student');
}

to

public function students()
{
    return $this->hasMany('Student')->orderBy('id', 'desc');
}