6

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

4 Answers 4

11

Simply use unescaped output:

<script>
    var array = {!! json_encode($array) !!};
</script>

Or

<script>
    var array = @json($array);
</script>

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

So, my complete answer is:

<script>
    var array = [].concat(@json($array));
</script>
5

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.

1
  • Knew it was something simple. Thank you.
    – Chris
    Aug 3, 2017 at 23:25
2

@fubar's solution worked for me. With one small change. The solution @json($geoJson) did not. But that was because I didn't put an array into the function but already a string. I had to extend @fubar's approach for me:

const data = JSON.parse(' {!! $geoJson !!} ');
console.log('data', data);

The single quotes were important.

1
  • 1
    Crazy! I looking for a solution and found my own answer! *lol / And it helps me ... Apr 2, 2022 at 17:51
0

The recommended approach in the latest Laravel 9 is:

<script>
    var app = {{ Js::from($array) }};
</script>

It uses the JSON.parse(...) approach under the hood. Same as in the answer of @Maik Lowrey

https://laravel.com/docs/9.x/blade#rendering-json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.