Laravel sort collection by date

Try something like this using sortBy():

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

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

Tags:

Php

Laravel