Reputation: 369
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:
When the result should be the following (items ordered by descent date when the total values are equal):
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
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