Search code examples
laravellaravel-5eloquentlaravel-collection

Sort Collection By id set


I have an array of ids that i want to sort a given column by them in the collection.

For example,

$suppliersOrder = [8,7,5,1,3,4];

$items = Items::get()->sortBy(function($model) use ($suppliersOrder) {
   return array_search($model->supplier_id, $suppliersOrder);
})->values();

This acts like ordering items as [1,3,4,5,7,8] instead of the given order. And if I try sortByDesc, likewise [8,7,5,4,3,1] but I couldn't figure out the way to actually sort them as my given array's order.

My ultimate goal is then running $items->groupBy('supplier.name') so I can have my desired order.


What Alexander Villalobos suggested in the comments, I changed my code like this:

$items = Items::get()->sortBy(function($model) use ($suppliersOrder) {
   return rsort($model->supplier_id, $suppliersOrder);
});

Indirect modification of overloaded property App\Item::$supplier_id has no effect


Solution

  • $suppliersOrder = [8,7,5,1,3,4];
    
    $items = Items::get()->sortBy(function($row,$key) use ($suppliersOrder) {
       return array_search($row->supplier_id, $suppliersOrder);
    });
    

    This should give you sorted collection of items by the order you described in $suppliersOrder. As per Laravel docs, the parameters to the callback function include one being the row for the collection and another being the key of that row in the collection.