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

wizgabriel18's avatar

order by date desc

Hi,

it seems that order by date descending is not working. I've tried order by id and it works. How can i make it work on order by date. And also how can i make two order by in one query.

Please Advise.

Thanks.

0 likes
6 replies
toniperic's avatar

My first guess is that the column isn't of date type in your database table.

As for two orders, you can just chain method calls, like so:

User::orderBy('created_at', 'desc')->orderBy('something', 'asc');

Hope I could help.

2 likes
pmall's avatar

please show code and table content

wizgabriel18's avatar

$topics = $this->topic->join('groups', function($join) { $join->on('topics.group_id', '=', 'groups.id'); })

                ->where('groups.type',0)        
        
                ->orderBy('topics.updated_at','DESC')

                ->orderBy('topics.reply_count','DESC')

                ->limit($limit)

                ->offset($offset)

                ->get()->toArray(); 

Fieldname: updated_at datetime

JarekTkaczyk's avatar

@wizgabriel18 Everything works, but you're making it load the data you wouldn't expect.

Joining the table without specifying which fields to select makes eloquent override duplicated fields by values from the joined table. I guess there are at least id and timestamps overriden. To make it work as expected use select( .. fields ..) or get([ .. fields .. ]).

However, I suppose you join the other table only to filter topics, which is ok, but you can make it easier with eloquent:

$this->topic->whereHas('group', function ($q) { // instead of join
    $q->where('type', 0);
})
    ->latest('updated_at')
    ->orderBy('reply_count', 'desc') // it could be latest as well, it's just a helper method
    ->limit($limit)->offset($offset)->get()->toArray()
Noman09's avatar

If you want to sort a date field which is not date_format and your date_format like below

"d-m-Y" then you can try this

$covid19Result = DB::select('select DATE_FORMAT(STR_TO_DATE(your_field_name,"%d-%m-%Y"), "%Y-%m-%d") as startDate, active_people, death_people, recover_people from covid_graphs ORDER BY startDate DESC');

Please or to participate in this conversation.