Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel sort collection by date

Tags:

php

laravel

I have this collection result:

$result = [{
    "date": "2016-03-21",
    "total_earned": "101214.00"
},
{
    "date": "2016-03-22",
    "total_earned": "94334.00"
},
{
    "date": "2016-03-23",
    "total_earned": "96422.00"
},
{
    "date": "2016-02-23",
    "total_earned": 0
},
{
    "date": "2016-02-24",
    "total_earned": 0
},
{
    "date": "2016-02-25",
    "total_earned": 0
}]

I want to sort the result by date:

$sorted = $transaction->sortBy('date')->values()->all();

But I don't get the expected result:

[{
    "date": "2016-02-23",
    "total_earned": 0

},
{
    "date": "2016-02-24",
    "total_earned": 0
},
{
    "date": "2016-02-25",
    "total_earned": 0
},
{
    "date": "2016-03-22",
    "total_earned": "94334.00"
},
{
    "date": "2016-03-21",
    "total_earned": "101214.00"
},
{
    "date": "2016-03-23",
    "total_earned": "96422.00"
}]

As you can see all with month 2 is sort properly. However at month 3 it start messed up. (the real result is longer than this and it messed up start at month 3)

Any solution to make it sort properly?

Thanks.

like image 634
ssuhat Avatar asked Mar 23 '16 04:03

ssuhat


2 Answers

I had the same problem. I created this macro.

Collection::macro('sortByDate', function (string $column = 'created_at', bool $descending = true) {
/* @var $this Collection */
return $this->sortBy(function ($datum) use ($column) {
    return strtotime(((object)$datum)->$column);
}, SORT_REGULAR, $descending);

});

I use it like this:

$comments = $job->comments->merge($job->customer->comments)->sortByDate('created_at', true);
like image 192
Raza Avatar answered Oct 22 '22 00:10

Raza


Try something like this using sortBy():

$sorted = $transaction->sortBy(function($col) {
    return $col;
})->values()->all();
like image 9
Alexey Mezenin Avatar answered Oct 21 '22 23:10

Alexey Mezenin