Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

EkoSyahputra's avatar

Laravel Collection sortBy date (String) not working as expected

Hi Guys I found some strange behaviour when the data deleted, it not sort same as before

This is the actual data

https://postimg.cc/Kkdp1Vw6

Then after I delete the purchase id 4898 and refresh it become

https://postimg.cc/JyFPFvrs

$collection->sortBy('expiry_date')

Anyone know how this happend?

0 likes
4 replies
MichalOravec's avatar

You have to change string to date or int in this example:

$collection->sortBy(function ($item) {
    return strtotime($item->created_at);
});
1 like
MichalOravec's avatar

Ok I now check those pictures and all of them have same date without time. So it can't know in which order they should be.

Better will be if you add next sortBy for example

$collection->sortBy('expiry_date')->sortBy('purchasing_id')

Please or to participate in this conversation.