'Passing php variables to javascript in laravel syntax errors

Question 1) When passing PHP variables to be used in javascript if the variables hold an array, it will result in an error relating to the attempted conversion of array to string when trying to pass these values in the following manner. Why do I have to json encode the value before it works when $var itself is already an array?

PHP Code

$var = ['test'];

Javascript

Let var = {!!$var!!};

Solution

Let var = {!!json_encode($var)!!} 

Question 2 when passing PHP variables that may have the value of null to javascript, it may result in a syntax error. For example,

PHP Code

$var = null;

Javascript

Let var = {{$var}};

Error

Var = ; (Syntax error)

Failed Solution

if({{$var}}){
    let var = {{$var}};

Solution

Let var = '{{$var');

Why does my attempted solution of only setting the value of the var when $var has a value fails?



Solution 1:[1]

simply put laravel echo in doouble quote

<script>
 let var1="{{$var}}";
</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 Salman ansari