For example, we have a model flight having 3 fields:
So I write that:
$flights = App\Flight::orderBy('created_at');
I get some $flight
objects ordered by create_time
. So I will change the name of flight by create_time
to first_flight
, second_flight
and so on...
But I want to display $flights
sorted by score. So I have to sort $flights
by score, but I have no idea how to achieve that.
So my question is, how to sort Eloquent ORM objects by a field(in my example, it's score
)?
Just get a collection:
$flights = App\Flight::all();
And then sort it with sortBy()
or sortByDesc()
without hitting DB:
$filghts->sortBy('created_at');
....
$filghts->sortBy('score');
If you want order by multiple column in same time use this
App\Flight::orderBy('created_at', 'DESC')
->orderBy('score', 'ASC')
->get();