It cannot handle nested data like that. It just uses the native array() cast on the extra key. The rest is ignored..
Instead you can write your own cast using an accessor. https://laravel.com/docs/9.x/eloquent-mutators#accessors-and-mutators
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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.
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?
Please or to participate in this conversation.