Passing (laravel) Array in Javascript

 

var app = @json($array);



you can use json_encode()


var array = {{ json_encode($theArray) }};


or parse the json string using JSON.parse()


var array = JSON.parse('{{ json_encode($theArray) }}');

 

Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:

<script>
    var app = <?php echo json_encode($array); ?>;
</script>
 

Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:

<script>
    var app = <?php echo json_encode($array); ?>;
</script>
However, instead of manually calling json_encode, you may use the @json Blade directive. The @json directive accepts the same arguments as PHP's json_encode function:

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

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



The @json directive is also useful for seeding Vue components or data-* attributes:

<example-component :some-prop='@json($array)'></example-component>
 

https://laravel.com/docs/5.8/blade#blade-and-javascript-frameworks

https://stackoverflow.com/questions/33326699/passing-laravel-array-in-javascript