To use the "sortBy" method in the Illuminate/Collections package to sort a collection by a specific key, follow these steps:
composer require illuminate/collections
use Illuminate\Support\Collection;
$collection = collect([
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Alice', 'age' => 20]
]);
$sorted = $collection->sortBy(function ($item, $key) {
return $item['age'];
});
$sortedArray = $sorted->all();
print_r($sortedArray);
The output of the above code will be:
Array
(
[0] => Array
(
[name] => Alice
[age] => 20
)
[1] => Array
(
[name] => John
[age] => 25
)
[2] => Array
(
[name] => Jane
[age] => 30
)
)
The collection is now sorted in ascending order by the "age" key. You can use the "sortByDesc" method to sort the collection in descending order instead.