PASSWORD RESET

Your destination for complete Tech news

How to sort a Laravel Collection?

585 0
< 1 min read

To sort a Laravel collection, you can use the sort method. This method will sort the items in the collection in ascending order according to their values.

Here’s an example:

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

// $sorted is now a collection containing [1, 2, 3, 4, 5]

You can also pass a callback to the sort method to specify a custom comparison function:

$collection = collect([
     ['name' => 'Alice', 'age' => 25],
     ['name' => 'Bob', 'age' => 30],
     ['name' => 'Charlie', 'age' => 35],
 ]);
 $sorted = $collection->sort(function ($a, $b) {
     return $a['age'] <=> $b['age'];
 });
 // $sorted is now a collection containing the items sorted by age in ascending order

If you want to sort the collection in descending order, you can use the sortByDesc method:

$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sortByDesc();

// $sorted is now a collection containing [5, 4, 3, 2, 1]

You can also use the sortBy method to sort the collection by a specific key:

$collection = collect([
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Charlie', 'age' => 35],
]);

$sorted = $collection->sortBy('age');

// $sorted is now a collection containing the items sorted by age in ascending order

Note that the sort, sortBy, and sortByDesc methods return a new sorted collection, they do not modify the original collection. If you want to sort the original collection, you can use the sort or sortBy methods in combination with the values method:

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

// $collection is now [1, 2, 3, 4, 5]

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.