nono.ma

Sort A Laravel Collection

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

March 2, 2017

LaravelCodeWeb