Laravel sort collection by date
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Handling date-based collections in your Laravel application can be challenging, especially when dealing with data spanning across multiple months. In this post, we'll tackle the issue of sorting a collection by date and provide you with all necessary information to ensure the process goes smoothly.
Firstly, let us take a look at the initial problem statement:php
$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
}]php
$sorted = $transaction->sortBy('date')->values()->all();
[{
"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"
}]php
$sorted = $transaction->sort(function ($a, $b) {
if (strtotime($a['date']) == strtotime($b['date'])) {
return 0;
}
// Sort by year first, descending.
if (strtotime($a['date']) < strtotime($b['date'])) {
return -1;
} else if (strtotime($a['date']) > strtotime($b['date'])) {
return 1;
}
// If years are the same, sort by month and day.
$aMonth = date('n', strtotime($a['date']));
$bMonth = date('n', strtotime($b['date']));
if ($aMonth == $bMonth) {
return 0;
}
// If months are the same, sort by day.
if (strtotime($a['date']) < strtotime($b['date'])) {
return -1;
} else if (strtotime($a['date']) > strtotime($b['date'])) {
return 1;
}
});