I 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?
To sort results in the database query, you'll need to use the orderBy() method, and provide the table field you want to use as criteria for ordering. This will give you more flexibility to build a query that will obtain only the results you need from the database. You'll now change the code in your routes/web.
Laracasts Veteran Sure it is slow, first it fetch all the record in one time, then it instantiate an eloquent object for each lines. It is not made to retrieve 10 000 objects.
The Laravel Orderby works by simply sorting the results of the query. So if the column has a list of 20 data, it can sort the list by the parameter provided. One can also create an order in an ascending or a Descending Order. By Ascending Order: $users = DB::table('users')->orderBy('name', 'asc')->get();
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'); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With