'How can I access JSON passed from PHP Laravel it in JS?
View
Right now, when I do
<pre>{{ $device->window }}</pre>
I see this
I want to access it in JS. Ex. device.screen.height, It's 926
I've tried
console.log(`{{ json_decode($device->window) }}`);
console.log(JSON.parse(`{{ json_decode($device->window) }}`));
console.log(JSON.parse(`{{ json_decode($device->window) }}`));
console.log(JSON.stringify(`{{ json_decode($device->window) }}`));
console.log(JSON.stringify(`{{ json_decode($device->window) }}`));
console.log(JSON.parse(`{{ json_encode($device->window) }}`));
console.log(JSON.parse(`{{ json_encode($device->window) }}`));
console.log(JSON.stringify(`{{ json_encode($device->window) }}`));
console.log(JSON.stringify(`{{ json_encode($device->window) }}`));
I kept getting
htmlspecialchars() expects parameter 1 to be string, object given
If I do :
console.log(JSON.parse(JSON.stringify({{ json_encode($device->window) }})));
I got
"{"innerWidth":"980","innerHeight":"1708","devicePixelRatio":"3","screen":{"width":"428","height":"926"}}"
I got so many "
Solution 1:[1]
You have to use different sintax for that :
{!! json_encode($device->window) !!}
But you should not access it like this. Its not good practice to mix languages.
Solution 2:[2]
Inside a script tag, you could do:
const myData = {{ $device->window }};
console.log(myData.screen.height);
Solution 3:[3]
The's a blade directive for that:
@php
$json = [ 1, new DateTime, (object)[], 'a' ];
@endphp
<script>
test = @json($json);
console.log(test)
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aleksandar ?oki? |
| Solution 2 | James |
| Solution 3 | shaedrich |

