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

vincent15000's avatar

orderBy not working

Hello,

I have a question about something which is from a quick look very simple.

I need to order datas by date.

$query
    ->orderBy('event_start_date', 'desc')
    ->orderBy('event_end_date', 'desc');

The problem is that it's not ordered.

And I have no other ordering in the query which could disturb.

It should work. But it doesn't.

Any idea ?

Thanks a lot.

V

0 likes
13 replies
vincent15000's avatar

@NoLAstNamE Here is the SQL query string.

select * from `events` order by `event_start_date` desc, `event_end_date` desc
1 like
tisuchi's avatar

@vincent15000 What do you mean by?

It should work. But it doesn't.

What exactly you are expecting and what you are getting?

2 likes
vincent15000's avatar

@tisuchi The data should be retrieved ordered by event_start_date descending, then event_end_date descending.

But I get the data in a different order.

When I apply only one order criteria, it works, but with both criteria, it doesn't work.

It's with Laravel 7.x.

1 like
tisuchi's avatar

@vincent15000 If so, then can you try this?

Event::orderByRaw('event_start_date DESC, event_end_date DESC')->get();
2 likes
vincent15000's avatar

@tisuchi I already tried this and it doesn't work better. Same result.

Could it be a MySQL configuration problem ?

1 like
tisuchi's avatar

@vincent15000 Interesting!

Is it possible to have the event_start_date and event_end_date are the same date?

2 likes
tisuchi's avatar

@vincent15000 I assume these kinds of records are creating conflicts.

In that case, you can set explicit order for the same date. For example:

Event::orderByRaw('CASE WHEN event_start_date = event_end_date THEN 0 ELSE 1 END')
               ->orderBy('event_start_date', 'desc')
               ->orderBy('event_end_date', 'desc')
               ->get();
1 like
vincent15000's avatar

@tisuchi I just understood the problem. It's a datetime field and the time is taken into account.

Is it possbile to order by date but only by date (without the time part) easily ?

Or do I have to select a formatted date with only the date and order by raw by using the formatted date ?

1 like
tisuchi's avatar
tisuchi
Best Answer
Level 70

@vincent15000 If you want to sort by date only, then try this:

Event::orderByRaw('DATE(event_start_date) DESC, DATE(event_end_date) DESC')->get();
2 likes
vincent15000's avatar

@tisuchi I tried with date_format, but it's not working. I didn't thought about date().

Thanks a lot, now it works ;).

2 likes

Please or to participate in this conversation.