Custom sorted collections in Eloquent

I have an array of ID as follows:

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

Using Eloquent I can find these identifiers using a function ->whereIn('id', $ids). This, as expected, will return the results in ascending order of Id, is there a way to return the results in the order in which the array is? alternatively, the easiest way to convert a collection to an array order $ids?

+3
source share
2 answers

If you need a specific order in which you want to include records, you will need to use Collection methods :

, sortBy , - :

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

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

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

shuffle.

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

$shuffled = $collection->shuffle();

$shuffled->all();

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

. Laravel Docs shuffle / sortBy.

, ->inRandomOrder() 5.2 , ->orderBy(DB::raw('RAND()')).

+7

sortBy :

$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
});
0

All Articles