laravel get data to pass to laravel blade but in json format

I have data that I am creating a chart using d3.js. I have that part working with hard coding the data as such

var data = {
            "name": ["A", "B", "C", "D", "E"],
            "vals": [48, 35, 34, 21, 11]

Where I am struggling is to get data into the javascript section of my blade template. I have tried to hardcode the following and I get an htmlspecialchars() expects parameter 1 to be string, object given.

$test = json_encode([
            "name" => ["A", "B", "C", "D", "E"],
            "vals"=> [48, 35, 34, 21, 11]

with this in the script area of the blade

var test = {{json_decode($test)}};

If I don't do json_decode I don't get an error but it transforms my " to &quot which obviously won't work.

I know I am just missing something here to make it work but maybe I will just do a new method and do an ajax call to get it.

Any thoughts or tips would be helpful



You need to output the value unescaped - var test = {!! $test !!}.

And if you're getting your values from a database or model, you could consider using the toJson() helper.


Simply use unescaped output:

    var array = {!! json_encode($array) !!};


    var array = @json($array);

Both variants in PHPStorm will highlight this line with an error - expression expected

So, my complete answer is:

    var array = [].concat(@json($array));


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.