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

amirsobhan's avatar

Eloquent Casting for properties of array

Hello guys!

I'm working on a project that needs to save some extra data per user such as profile_picture, phone_verified_date, and something like that. I didn't want to store these data in separate columns in the database, so I create one column and named that extra and stored all this stuff as JSON on that. I also use the Laravel Eloquent Casting feature to work with JSON data in the database.

My question is: Can I use this feature to cast phone_verified_date that's in array to DateTime format ?

I was trying this code to cast my attributes

 protected $casts = [
        'extra' => 'array'
        'extra.phone.phone_verified_at' => 'immutable_datetime',
        'extra.email.email_verified_at' => 'immutable_datetime'
];

The output of dd($user->extra) :

array:2 [
  "phone" => array:1 [
    "phone_verified_at" => "2022-11-04T13:01:37.638407Z"  // <----  This property should cast to DateTime
  ]
  "email" => array:1 [
    "email_verified_at" => "2022-11-04T13:01:37.638448Z" // <-----
  ]
]

In this code, the extra attribute is JSON and was cast to an array with no problem but the other didn't cast to DateTime.

Anyone had an idea what should I do?

0 likes
2 replies

Please or to participate in this conversation.