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

robcollier's avatar

Ordering by date inside Json column

I have a json column in database which contains a date:

{
  "dates": [
    {
      "day": 1,
      "date": "2022-11-14 00:00:00"
    },
    {
      "day": 2,
      "date": "2022-11-16 00:00:00"
    }
  ]
}

I have cast the column as an array

protected $casts = ['dates' => 'array'];

Is there any way I can cast the dates within as Carbon objects? I need to be able to order_by on said dates, is this even possible?

0 likes
5 replies
wingly's avatar

If you want to sort the dates column based on the date key then you can cast the column to a collection instead of an array and use sortBy on the collection

1 like
MisstypingMeerkat's avatar

You would have to define your date/day as a model attribute first, then you can access it everywhere and also sort by this attribute:

class MyModel extends Model {
 ...
    public function getDayAttribute()
    {
		//untested, just for illustration!
		$dates = json_parse($this->jsonColumn);
		return $dates[0]['date'];
    }
}

So now you can access it just like this:

dd($myModel->day);

this also gives you access to all the collection methods (https://laravel.com/docs/9.x/collections#available-methods), including sorting:

$sorted = $myModels->sortBy('day');
 
dd($sorted->values()->all());
1 like
MohamedTammam's avatar

If you are asking to do so using Laravel collection.

$collection = Model::all();
$sorted = $collection->sortBy(function ($item, $key) {
    return Carbon\Carbon::parse($item->dates['date']);
});
1 like

Please or to participate in this conversation.