Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a controller that passes a array to the blade file call 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 possible rendering it to html in JSON via Blade then pulling the JSON from the html in JavaScript

share|improve this question
up vote 1 down vote accepted

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

share|improve this answer
    
Thanks for your reply, blade does't echo out the variables and i end up with this passed the the client side var availableTags = [@foreach($data as $k => $info) "{{ $info['name'] }}", @endforeach ]; – user2929209 Jan 4 '16 at 16:56
    
What version of laravel are you using? Keep in mind that even though this is a laravel blade file, you can still use native PHP - so try doing this: <pre><?php print_r($data); ?></pre> and ensure you are getting the passed data. – Derek Jan 4 '16 at 17:02
    
5.1, but not sure how to check. I know the data is being passed as its echoed to the html aswell, i'm trying to add it to the javascript along side what is already rendered – user2929209 Jan 4 '16 at 17:18
    
Have you put the code in a script tag? – Derek Jan 4 '16 at 17:20
    
Yeah it works now, I had to put the variable on the index.blade.php page inserted of having it in the main.js file that is included on the index.blade.php. Thanks for your help !! :) – user2929209 Jan 4 '16 at 17:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.