2

For example, we have a model flight having 3 fields:

  • created_at: the time when the flight created
  • name: the name of the flight
  • score: the score of the flight

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)?

Sayakiss
  • 6,878
  • 8
  • 61
  • 107
  • 1
    @theomessin Then I will have `$flights1 = App\Flight::orderBy('created_at');`, `$flights2 = App\Flight::orderBy('score');`. I just want to have one `$flights` and sort in place... – Sayakiss Sep 09 '16 at 04:11

2 Answers2

2

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');
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

If you want order by multiple column in same time use this

App\Flight::orderBy('created_at', 'DESC')
    ->orderBy('score', 'ASC')
    ->get();
Hamelraj
  • 4,676
  • 4
  • 19
  • 42