Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing (laravel) Array in Javascript

I want to pass/store Laravel array in JavaScript variable. I used ->all() so I get the result like this rather than object:

array:83 [▼   0 => 1   1 => 11   2 => 12   ... ] 

I can access this in view using {{ $theArray }}.

However whatever I tried, I couldn't make this to javascript array.

I tried

var array = {{ $theArray }};

var array = {{{ $theArray }}};

I feel like I'm close but I couldn't figure it out

like image 669
senty Avatar asked Oct 25 '15 05:10

senty


People also ask

Can you pass PHP array to JavaScript?

You can easily use PHP array in javascript you only need to convert PHP array into JSON format Using json_encode() function. PHP array can be converted to JavScript array and accessible in JavaScript. Whatever the array type is, a single or multidimensional or indexed or associative array.

How to assign PHP array to JavaScript array?

PHP array can be used in JavaScript, whatever the array is a single or multidimensional or indexed or associative array. You can convert PHP array to JavaScript array easily with a single line of code. Using json_encode() function, PHP array can be converted to JavScript array and accessible in JavaScript.


1 Answers

var app = @json($array); 

Works like a charm

like image 162
Alex Alekser Avatar answered Sep 20 '22 16:09

Alex Alekser