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?

itsliamoco
  • 1,028
  • 1
  • 12
  • 28
  • 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. – pioneer Jul 25 '16 at 18:33

1 Answers1

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.

Jannie Theunissen
  • 28,256
  • 21
  • 100
  • 127