3

I'm passing a Laravel Model's dataset to a vuejs2 component via ajax/ axiom and rendering it fine.

However, there is a JSON column in the model which stores a valid json object, the data could look like so: {'key':'value'} and it's worth noting that I'm working with it without issue in Laravel Controllers etc thanks to a Mutator on the Model ( protected $casts = [ 'the_json_column' => 'array']; )

When I pass this model to vuejs via axiom / ajax all of the properties in the array behave as usual, I can iterate over them and render them in the vuejs2 component DOM.

Until I interact with 'the_json_column' which despite Laravel's mutator is being passed to vuejs2 as a string, e.g. "{'key':'value'}"

Is there a more elegant way than doing a JSON.parse(data.the_json_column).key in my vuejs2 component every time I want to interact with the JSON column data?

Lewis
  • 624
  • 9
  • 16
  • you can use [Laravel Eloquent: API Resources](https://laravel.com/docs/5.6/eloquent-resources) it's very useful for the situations like this. – Maraboc Mar 02 '18 at 10:14
  • Are you able to [parse the json string in php](https://stackoverflow.com/questions/4343596/how-can-i-parse-a-json-file-with-php) as an associative array? Then you can simply [pass that array to the view](https://laracasts.com/discuss/channels/laravel/how-to-pass-json-array-into-view?page=1). – Udayraj Deshmukh Mar 02 '18 at 10:18
  • How does the controller part look like? I hade this problem when displaying JSON from a JSON Column, from MySQL. I used a `->map` to convert it to an array. – Anuga Mar 26 '18 at 11:48

2 Answers2

2

The solution I've gone with is decoding the data property manually in the VueJS2 template,

e.g. JSON.parse(data.key_which_is_actually_json).property_in_the_object

Any laravel based code (accessors, mutators etc) will fail when the property is transferred to VueJS2 component over HTTP as VueJS2 isn't smart enough to check properties in data receive and decode them.

VueJS2 seems to only decode the top level of properties in data received.

Lewis
  • 624
  • 9
  • 16
0

You may create your own Accessor and then convert the column to an array manually before retrieving the model.

public function getTheJsonColumnAttribute($value)
{
    return json_decode($value, true);
}

While it may seem laravel simply treated that column as a mere 'string' value when coming out, you can further validate that there is indeed a conversion.

  • 1
    This wouldn't work because the property exists as an array in the PHP already - it's the transfer over http from Laravel to the VueJS2 component that convert's it to a string and VueJS2 isn't smart enough to auto decode properties that look like valid json. – Lewis Mar 07 '18 at 13:42