5

I have the following...

$people = array(5, 2, 9, 6, 11);

$people_collection = People::find($people);

But when I dump and die $people_collection the collection is ordered by the ID ASC, how can I keep the collection, in the same order as the $people array?

1
  • This is because find internally calls mysql IN clause which returns the rows in ascending order of the Ids passed. You can manually sort the array or use the method explained by Jannie. Commented Jul 25, 2016 at 18:33

1 Answer 1

9

Collections has a sortBy function that takes a custom callback:

$people_collection = People::find($people)
   ->sortBy(function($person, $key) use($people) {
         return array_search($person->id, $people);
      });

See the docs.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.