Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement