Laravel collection sort by

Do you know that Laravel provide some function that let us easily to do sorting for our collection?

Patrick Wan
3 min readMay 21, 2022

--

Today we gonna talk about these functions:

  • sort()
  • sortBy()
  • sortByDesc()
  • sortDesc()
  • sortKeys()
  • sortKeysDesc()
  • sortKeysUsing()

sort()

The sort method sorts the collection. The sorted collection keeps the original array keys, so in the following example we will use the values method to reset the keys to consecutively numbered indexes:

$collection = collect([5, 3, 1, 2, 4]);$sorted = $collection->sort();$sorted->values()->all();// [1, 2, 3, 4, 5]

sortBy()

The sortBy method allow you to sort by specific key in collections.

$collection = collect([  ['name' => 'Item A', 'price' => 200],  ['name' => 'Item B', 'price' => 100],  ['name' => 'Item C', 'price' => 150],]);$sorted = $collection->sortBy('price');$sorted->values()->all();/*[ ['name' => 'Item B', 'price' => 100], ['name' => 'Item C', 'price' => 150], ['name' => 'Item A', 'price' => 200],]*/

Alternatively, you may pass your own closure to determine how to sort the collection’s values:

$collection = collect([  ['name' => 'Item1', 'colors' => ['Black', 'Mahogany']],  ['name' => 'Item2', 'colors' => ['Black']],  ['name' => 'Item3', 'colors' => ['Red', 'Beige', 'Brown']],]);$sorted = $collection->sortBy(function ($product, $key) {  return count($product['colors']);

--

--

Patrick Wan

My name’s Patrick. I’m a Software Developer, experience in Laravel, Vue Js, React Js, Livewire, Jquery, Codegniter, NPM, GIT. I have 5 years plus experience.