Laravel - Collections - Method 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]
If your sorting needs are more advanced, you may pass a callback to sort
with your own algorithm. Refer to the PHP documentation on uasort
, which is what the collection's sort
method calls utilizes internally.
If you need to sort a collection of nested arrays or objects, see thesortBy
andsortByDesc
methods.