This is an example of sorting a Laravel collection by > 1 attribute with different sort directions. Unlike some of the other solutions mentioned in this thread it works with any type PHP can normally sort and doesn't require hashing.
That works because of how PHP's comparison functions work:
Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value
The <=>
operator is PHP's combined comparison operator, or 'spaceship' operator. It makes writing custom sort functions very easy.
If you need to do a compound sort but every attribute is being sorted in the same direction, you can use sortBy
/sortByDesc
instead of writing your own sort function.
$taps->sortBy(fn ($tap) => [$tap->rating, $tap->price])