ssuhat
ssuhat

Reputation: 7656

Laravel sort collection by date

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.

Upvotes: 15

Views: 50689

Answers (3)

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

Try something like this using sortBy():

$sorted = $transaction->sortBy(function($col) {
    return $col;
})->values()->all();

Upvotes: 10

Raza
Raza

Reputation: 3383

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);

Upvotes: 13

Dzung Cao
Dzung Cao

Reputation: 37

You may try

$transaction->groupBy('date');

And be sure that $transaction is a collection;

Upvotes: -10

Related Questions