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

simcha's avatar

Order by date in json column

order_by('data->date') is sorted by data->date like string instead of by date.

the values data->date are like: "2022-01-05"

0 likes
8 replies
kmoore's avatar

If you're using eloquent the method you want is orderBy()

Model::orderBy('data->date');
simcha's avatar

@kmoore This is what I try but it arranges it by string and not by date For example 2022-05-11 will be after 2022-11-11

simcha's avatar

@Sinnbeck That's not the point, the problem is that it treats the entry as text and not as a date

Sinnbeck's avatar

@simcha Not sure I understand the problem then? Year-month-day. I assume its sorted in the same way as in php?

$arr = [
        '2022-08-11',
        '2022-01-22',
        '2022-05-01',
        '2022-11-11',
    ];
    sort($arr);

    //returns
[
"2022-01-22",
"2022-05-01",
"2022-08-11",
"2022-11-11"
]

But could you perhaps move the data to another table ? Then you have full control over it.

kmoore's avatar

@simcha If you need it cast as a date before the orderBy() you could write a raw query to do it in the sql. Or you could write an accessor and use the collection sort() method.

Raw query for example (not tested):

Model::selectRaw('JSON_EXTRACT(data, "$.date") AS dataDate')->orderByRaw('CAST(dataDate AS DATE) ASC');
jlrdw's avatar

@simcha json is text. I would store data in database then ORDER BY date.

Please or to participate in this conversation.