ideas icon indicating copy to clipboard operation
ideas copied to clipboard

Make ::find() on eloquent preserve order of passed ids in collection result

Open garygreen opened this issue 3 years ago • 0 comments

At the moment when you find ids:

$users = User::find([12, 22, 100]);

The returned users could come back in any order. This makes code that uses external search services more tricky:

$userIds = $elasticSearch->females()->sortByAge()->getIds();
$users = User::find($userIds); // Order is not guaranteed. Users may come back in any order.

As you have essentially defined a specific order to the array of ids you passed to it - it would be awesome if it could preserve that order in the collection result.

At the moment you would have to do this:

$userIds = $elasticSearch->females()->sortBy('age')->getIds();
$users = User::find($userIds)->sortBy(function($user) use ($userIds) {
  return array_search($user->getKey(), $userIds);
}); // Users will now preserve order.

garygreen avatar Jun 02 '21 13:06 garygreen