Cristian Bustos
Cristian Bustos

Reputation: 369

Sort collecttion by date DESC using Laravel and Collection

I have a collection where I am ordering the "total" value in a descending way. When the "total" values are the same, I must order the items by descending date.

$collection->sortByDesc('total');

To sort the elements by descending date when the totals are equal, I have used sort and sortByDesc but the elements are still not sorted.

//First method
$collection->sortByDesc('created_at')->sortByDesc('total');

//Second method
$collection->->sort(function($a, $b){
   if($a->total === $b->total)
   {
      return strtotime($a->created_at) - strtotime($b->created_at);
   }
})->sortByDesc('total');

Neither option works for me and I still have the same result:

enter image description here

When the result should be the following (items ordered by descent date when the total values are equal):

enter image description here

What am I doing wrong?

PS: It does not help me to sort by "total" and then by "date" since the "total" value is the one that should be a priority.

Upvotes: 2

Views: 10736

Answers (1)

Rwd
Rwd

Reputation: 35180

sortByDesc will override the sorting you've done in your sort function.

Also, strtotime($a->created_at) - strtotime($b->created_at) will order the dates in ascending order not descending order.

The following should give you what you're after:

$collection->sort(function ($a, $b) {
    if ($a->total === $b->total) {
        return strtotime($a->created_at) < strtotime($b->created_at);
    }

    return $a->total < $b->total;
});

Lastly, assuming that created_at and updated_at are Carbon instances you shouldn't need to use strtotime:

$a->created_at < $b->created_at

Upvotes: 7

Related Questions