laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 31 forks source link

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

Open garygreen opened 3 years ago

garygreen commented 3 years ago

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.