Reputation: 2603
I am struggling with trying to identify the best approach for sending the PHP array as JSON string or JSON Object to frontend JavaScript using Laravel 5.6 Blade template.
It seems like when I do the following in Blade template file it never convert it to string.
@php $vueModel = [ ...] @endPhp
<script>
sessionStorage.setItem('vueModel', {!! json_encode($vueModel) !!} );
...
</script>
It shows as an [Object Object] in the Chrome dev tools.
So after this if I try to do the following it will not work (there will be errors):
let model = JSON.parse(sessionStorage.getItem('vueModel'));
But if I do the following trick, then it spit out the string.
Please notice the single quote surrounding '{!! ... !!}'
<script>
sessionStorage.setItem('vueModel', '{!! json_encode($vueModel) !!}' );
...
However, this has its own problem because now I get the string with backslash encoded quotes and then I will have to fix that.
So what is the clean way to send the PHP array as a either JSON Object or JSON String without any encoding to Frontend JavaScript using laravel 5.6 Blade template language ? What is the recommended approach in this situation?
Upvotes: 2
Views: 1420
Reputation: 2603
Found a way that appears to be recommended approach by Laravel 5.6 Blade engine:
sessionStorage.setItem('vueModel', JSON.stringify(@json($vueModel)));
Useing @json blade directive is a nice and convenient way for converting the PHP Array to JSON Object for Frontend.
Then basically to avoid the encoding issue... on front end you do the following:
let vModel = JSON.parse( ...your JSON string representation of the PHP Array)!
So this way you get a clean JSON Object on JS frontend without worrying about the encoding issue.
Upvotes: 1