Laravel collection sort by
Do you know that Laravel provide some function that let us easily to do sorting for our collection?
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 =…