Search

Laravel 5 Collections: Sort a Collection in Descending Order With sortByDesc

April 22, 2018 —John Koster

The sortByDesc method operates exactly the same as the sortBy method. The only differences is that the sortByDesc method does not define a $descending parameter. The sortByDesc method internally makes a call to the sortBy method passing true as the argument for the $descending parameter.

#Signature

1public function sortByDesc(
2 $callback,
3 $options = SORT_REGULAR
4);

#Example Use

The following calls to the sortBy and sortByDesc methods are functionally equivalent:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 ['name' => 'Marshall']
6]);
7 
8$sorted = $collection->sortBy('name', SORT_REGULAR, true);
9 
10$sorted = $collection->sortByDesc('name', SORT_REGULAR);
11 
12$sorted = $collection->sortByDesc('name');

#Using sortByDesc With Higher Order Messages

Like the sortBy method, the sortByDesc method can also be used with higher order messages. We will adjust the example explored in the sortBy section:

The PeripheralDevice Class:

1class PeripheralDevice
2{
3 public $name = '';
4 
5 public function __construct($name)
6 {
7 $this->name = $name;
8 }
9}

sortByDesc with Higher Order Messages:

1$devices = collect([
2 'monitor',
3 'keyboard',
4 'printer',
5 'mouse',
6 'microphone'
7 ])->transform(function ($device) {
8 return new PeripheralDevice($device);
9 })->sortByDesc->name;

After the above code has executed, the $devices variable would reference a collection instance containing PeripheralDevice objects that are sorted in reverse-alphabetical order.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.