Home:ALL Converter>Laravel type casting for nested array

Laravel type casting for nested array

Ask Time:2019-10-21T15:15:29         Author:Symphony0084

Json Formatter

How do you create a cast definition for an Eloquent Model that allows automatic handling of nested array encoding/decoding?

As far as I can tell, the 'array' cast only encodes and decodes the first tier of the array. If you have a nested array, the nested levels will only be returned as strings instead of arrays.

Laravel allows you to cast types of data for use with Eloquent Models, so that values can be passed to and from the DB without continuously having to use json_decode and json_encode, etc.

This is where their docs discuss type casting PHP arrays <-> MySQL JSONs:

https://laravel.com/docs/master/eloquent-mutators#array-and-json-casting

The problem is that if you have a nested PHP array and you want to cast it to/from MySQL, Laravel's array casting only works in the first level.

An array or object with multiple nested levels will have its nested levels stored and retrieved as strings instead of as arrays.

For example:

If this is a property in your Model:

protected $casts = [
    'nestedArray' => 'array'
]

And then you try to store this nested array to your DB:

$nestedArray = [
    'sample1key' => 'sample1data',
    'sample2key' => ['nested2key' => 'nested2data']
]

If you use the above PHP array and store it in the MySQL DB as a JSON, and then retrieve it, instead of the original nested array you will end up with this:

$nestedArray = [
    'sample1key' => 'sample1data',
    'sample2key' => "['nested2key' => 'nested2data']"
]

Note the new double quotation marks which means that it is a string and you then have to use json_decode on sample2key to access its elements programmatically which is less than ideal.

This example seems simple enough, but its inconvenient at scale. I am trying to find a way to create a cast that encodes/decodes ALL of the nested levels of the array - not just the first level.

Author:Symphony0084,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/58481445/laravel-type-casting-for-nested-array
yy