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

ardf16's avatar

Very wierd sorting issue

Hi, i have this query:

Post::select(DB::raw("DATE_FORMAT(updated_at, \"%m-%Y\") AS updated_month"))
->groupBy('updated_month')
>orderBy(DB::raw("STR_TO_DATE(updated_month, \"%m-%Y\")"), 'DESC')
>get();

wchich outputs query:

select DATE_FORMAT(updated_at, "%m-%Y") AS updated_month from `posts` group by `updated_month` order by STR_TO_DATE(updated_month, "%m-%Y") desc

Eloquent returns collection unsorted... The same exact query in heidisql returns dates properly sorted.

what's going on here?

0 likes
4 replies
meeshka's avatar

@ardf16 Try

Post::select(DB::raw("DATE_FORMAT(updated_at, \"%m-%Y\") AS updated_month"))
->groupBy('updated_month')
>orderBy('updated_month', 'DESC')
>get();
Cronix's avatar

It would also probably be better to sort by Y-m rather than m-Y if you're trying to get an actual chronological order

rsvb's avatar

You can use month and year and why not 1 string in raw??

year(now()), month(now())

ardf16's avatar

Ok i think friday afternoon fever got me. What about:

DB::raw("DATE_FORMAT(updated_at, \"%m-%Y\") AS updated_month"))
->groupBy('updated_month')
->orderBy('updated_at', 'DESC')
->get();

Please or to participate in this conversation.