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

1
  • 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... Commented Sep 9, 2016 at 4:11

2 Answers 2

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');
Sign up to request clarification or add additional context in comments.

Comments

0

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

App\Flight::orderBy('created_at', 'DESC')
    ->orderBy('score', 'ASC')
    ->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.