How to use the "sortBy" method to sort a collection by a specific key in illuminate/collections?

To use the "sortBy" method in the Illuminate/Collections package to sort a collection by a specific key, follow these steps:

  1. First, ensure you have the Illuminate/Collections package installed in your Laravel project. You can install it via Composer by running the following command:
composer require illuminate/collections
  1. Import the required Illuminate collections class to your file where you want to sort the collection. Include the following line at the top of your file:
use Illuminate\Support\Collection;
  1. Create a new collection instance. You can either create a collection from an existing array or fetch it from a database query. For this example, let's create a simple collection from an array:
$collection = collect([ ['name' => 'John', 'age' => 25], ['name' => 'Jane', 'age' => 30], ['name' => 'Alice', 'age' => 20] ]);
  1. Use the "sortBy" method to sort the collection by a specific key. The "sortBy" method requires a callback function that returns the value you want to sort by. In this case, let's sort the collection by the "age" key:
$sorted = $collection->sortBy(function ($item, $key) { return $item['age']; });
  1. The "sortBy" method will return a new sorted collection. You can retrieve the sorted array by using the "all" method:
$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.