How to order result in laravel using relationship.
have a model called School and it has many Students .
Here is the code in my model:
public function students()
{
return $this->hasMany('Student');
}
I am getting all the students with this code in my controller:
$school = School::find($schoolId);
and in the view:
@foreach ($school->students as $student)
Now I want to order the Students by some field in the
students
table. How can I do that?ANS:
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')
}
No comments:
Post a Comment
Please Comment Here!