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

starmatt's avatar

Array casting in laravel (eloquent mutators) returns a string?

Hello everyone

I have been reading about attributes casting in eloquent models. Laravel suggests here that I can use a Json serialized string in a TEXT field of my database and then access it as an array.

Here is what I've done:

In my migration:

$table->text('address');

In my model:

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

Here's what happens when I create a new row in my database (in a controller):

$address = collect($user->Address)->only(['street','post_code','city','country'])->toJson();

$example = Example::create([
    'address' => $address
]);

Now, this works fine I think, here is what I have in my 'address' column:

"{\"street\":\"100 rue Therese\",\"post_code\":75000,\"city\":\"Paris\",\"country\":\"France\"}"

My issue is that when I try to access this ($address = $example->address) for instance with dd(), what I get is a string:

"{"street":"100 rue Therese","post_code":75000,"city":"Paris","country":"France"}"

instead of an array, as implied in the laravel documentation. Moreover, when I try to directly access a value of the array, I get an 'illegal offset' error, example:

$address = $example->address['city'];

Illegal string offset 'city'

Am I misunderstanding the doc?

Thanks everyone for your attention!

(note: this is an example, I'm trying to be concise but if you need more information please tell me!)

0 likes
2 replies
Euclides's avatar

I have the same issue here, any solution?

cedamorim's avatar

Try this


$address = $example->address;

$city = $address['city'];

Please or to participate in this conversation.