When using Laravel, it is common to sort Eloquent models obtained with the query builder by calling ->orderBy('created_at', 'DESC')
, for instance. But this is not always possible when arranging an Eloquent Collection
(Illuminate\Database\Eloquent\Collection
). To do this, we need to pass a sorting closure to the ->sortBy()
method. (An example would be that our collection has the property order
.) In that case, we could just call the following:
$items = $items->sortBy(function($item) {
return -$item->order;
});
If your data is simple you can also use native PHP ways of sorting arrays like asort
, arsort
, ksort
, or krsort
.