laravel get data to pass to laravel blade but in json format
Asked Answered
A

4

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

Amphipod answered 3/8, 2017 at 23:11 Comment(0)
N
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.

Napolitano answered 3/8, 2017 at 23:13 Comment(1)
Knew it was something simple. Thank you.Amphipod
D
13

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>
Dissymmetry answered 17/1, 2019 at 10:29 Comment(0)
N
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.

Napolitano answered 3/8, 2017 at 23:13 Comment(1)
Knew it was something simple. Thank you.Amphipod
W
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.

Wittol answered 29/10, 2021 at 9:4 Comment(1)
Crazy! I looking for a solution and found my own answer! *lol / And it helps me ...Wittol
H
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

Honky answered 13/12, 2022 at 8:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.