53

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

10 Answers 10

218
var app = @json($array);

Works like a charm

Sign up to request clarification or add additional context in comments.

7 Comments

your answer was flagged as low quality because of length. Consider expanding your answer to explain how it works.
Your answer is the most concise and works like the others. Don't know why it' not the selected answer. What @DerekBrown said doesn't makes sense, as the other answers also doesn't explain how works.
Thumps up for this answer. It uses the laravel blade directive instead of the manual way above.
I learnig more one method fantastic, thanks friend work with charm
@MateusFelipe it was not selected answer because the OP was from 2015 and this answer is 2018, that's a nice way, and that's the version I use now everyday. Fyi, I marked it as selected answer :)
|
30

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) }}');

2 Comments

I'm not sure why I got Unexpected token if using this {{ }}. then I change to {!! !!} then this will work. maybe cuz of laravel version
{{ }} will escape the output string, hence the error. while {!! !!} doesn't, it outputs the string as is. check the documentation laravel.com/docs/5.6/blade#displaying-data
21

This works for me :)

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

1 Comment

worked well for me. You could also use blade helper @json($theArray) . still works the same
14

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

Comments

3

you have enclodse with quotes,or use json_encode()

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

or, if the value in an array()

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

Without having quotes around javascript variable, it will throw you error. you can check in your console.

1 Comment

htmlentities() expects parameter 1 to be string, array given
2

Using the blade directive @json was the simplest thing that worked for me.

<script>
    var jsArray = JSON.parse(@json($phpArray, JSON_PRETTY_PRINT));
</script>

Here is the full list of parameters for @json and json_encode https://www.php.net/manual/en/json.constants.php

  • Both jsArray and JSON.parse() are javascript
  • The blade directive is @json()
  • No curly braces needed with directives

1 Comment

Using json_encode($phpArray) instead of $phpArray was what worked for me
1

this one worked for me.

let array = JSON.parse('{!! json_encode($array) !!}');

Comments

0

Sometimes all() is not enough to convert your Laravel collection to array. I encountered this issue trying to pass the collection of custom type objects to JS via Laravel view.

To get the array on the front end JS you have to apply Collection::values() method before all() method.

So:


// In your HTTP controller
$collection = collect([myObj1,myObj2]); // The collection filled with custom type objects.

$myArray = $collection->values()->all(); // Then converted to an array. Just `all()` is not enough;

return view('myview', $myArray);
{{-- In your myview.blade.php --}}

<script>window.myArray= @json($myArray)</script>

Then in your JS window.myArray you get an array [], not an object {}.

A Bit Of Details

This is probably happens due to the fact that when an array indexes are not ascending ordered PHP considers the indexes to be object keys, then it considers the array to be an object. Thus the transformation to an object instead of an array. Laravel collection values() resets the array keys. I suspect it applies PHP array_values() under the hood.

Comments

0

In my case I needed a Laravel Collection to pass through as an iterable array on the JavaScript client. The following worked:

return array_values($job_summaries->toArray());

Comments

-1

Simply, escape the special characters using the blade syntax. Try this.

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

Best part, you don't need to parse it to its object form in JavaScript.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.