user2929209
user2929209

Reputation:

Laravel JavaScript passing an array from backend to a array in JavaScript

I have a controller that passes an array to the blade file calls it $data From there I echo the data to the page via blade like {{ $data[0]['name] }}

The problem is I also want the data to be inside an array in javascript.

How can this be accomplished? Is it best to just request the data again via AJAX or is there a way to get the data out of Blade and into javascript? Or possibly rendering it to HTML in JSON via Blade and then pulling the JSON from the HTML in JavaScript

Upvotes: 4

Views: 4531

Answers (1)

Derek Pollard
Derek Pollard

Reputation: 7165

So in doing this, you'd simply pass the data to javascript the same way you would with php: <script> var a = ['{{$data[0]['name] }}','{{$data[0]['name] }}'];</script>

Or, if you don't want to go through each individual one and add them by hand, use laravels built in foreach loop:

var a = [@foreach($data as $k => $info)
   '{{ $info }}',
@endforeach ]

This just depends on exactly how you plan on going about this

Upvotes: 4

Related Questions