20

I have an array of ID's as follows:

$ids = [5,6,0,1]

Using Eloquent I am able to search for these Id's using the ->whereIn('id', $ids) function. This as expected will return the results in the ascending order by Id, is there a way I can return the results on the order the array is in? alternatively whats the easiest way to convert the collection in the order of the $ids array?

InvalidSyntax
  • 9,131
  • 20
  • 80
  • 127

3 Answers3

35

If there's a specific order you'd like the records in, you'd have to use the Collection Methods:

To get your ID's in the very specific order you've specified, you can make use of the sortBy method as follows, where collection is your collection of models:

$ids = [ 5, 6, 0, 1];

$sorted = $collection->sortBy(function($model) use ($ids) {
    return array_search($model->getKey(), $ids);
});

// [ 5, 6, 0, 1] // (desired order)

To randomize your collection you can make use of the shuffle method.

$collection = collect([1, 2, 3, 4, 5]);

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] // (generated randomly)

See the Laravel Docs on shuffle and/or sortBy for more specific requirements.

If you don't really have a specific order in mind, you can use ->inRandomOrder() in version 5.2 and up, older versions would require the raw query using ->orderBy(DB::raw('RAND()')).

Stephen Lake
  • 1,582
  • 2
  • 18
  • 27
11

See answer to MySQL order by field in Eloquent. It is possible to order the data in your SQL query. Other answers here are suggesting you sort the data after you've already fetched it in "wrong" order.

Your code should look like this:

$ids = [5,6,0,1];

$collection = YourModel::whereIn('id', $ids)
    ->orderByRaw('FIELD (id, ' . implode(', ', $ids) . ') ASC')
    ->get();
Luka Peharda
  • 1,003
  • 8
  • 18
-2

You can pass a function into the sortBy method to perform complex sorting:

$ids = [5,6,0,1];

$collection = YourModel::whereIn('id', $ids)->sortBy(function($model) use ($ids) {
    // Access your array order here and modify the sorting here
});
Tim Sheehan
  • 3,994
  • 1
  • 15
  • 18
  • 2
    This does not work, as Model::whereIn() does not return a collection but a query builder object. To work there should be a ->get() call between whereIn and sortBy – ak93 Jan 10 '19 at 22:42