Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort Illuminate Collection by multiple columns in Laravel 5.1?

I have a an instance of Laravel's Illuminate Collection. The array contains multiple properties.

I need to be able to sort the collection based on 2 different attributes.

I want to first sort by the attribute that is called "sort" and then by an attribute called "title".

Additionally, I have another collection that I like to sort it by the column "sort" if the value of sort is not null, then shuffle the items that have null for "sort" value.

How can I do this type of sort?

like image 969
Junior Avatar asked Nov 14 '15 21:11

Junior


2 Answers

If you're using PHP 7, you can use the spaceship operator:

$collection->sort(function ($a, $b) {
    return $a->sort === $b->sort ? $a->title <=> $b->title : $a->sort <=> $b->sort;
});

The <=> symbol is called the spaceship operator (or technically: the combined comparison operator). You can read more about it in the RFC.

like image 156
Joseph Silber Avatar answered Oct 26 '22 22:10

Joseph Silber


You can provide a callback function to Collection::sort:

$collection->sort(function($a, $b) {
   if($a->sort === $b->sort) {
     if($a->title === $b->title) {
       return 0;
     }
     return $a->title < $b->title ? -1 : 1;
   } 
   return $a->sort < $b->sort ? -1 : 1;
});

This is documented here.

like image 41
svrnm Avatar answered Oct 26 '22 23:10

svrnm