Reputation:
I am new to Lavarel
and I wrote this portion of code to add my collection to a javascript array and it does not seem to work.
$(document).ready(function() {
var data = [];
@foreach($products as $product )
data.push({'{{ $product->id }}' : '{{ $product->name }}'});
@endforeach
// Im trying to get a variable which looks like this
// data: [
// {
// id: 'The ID goes here',
// text: 'Text to display'
// },
// // ... more data objects ...
// ]
});
Kindly help me solve this problem
Upvotes: 0
Views: 1580
Reputation: 40653
You can simply write:
$(document).ready(function() {
var data = {!! json_encode($products) !!}; // Note the {!! !!} to not encode html entities since we'll probably have quotes in here
});
Upvotes: 1
Reputation: 118
Why dont you just convert the collection to JSON in your Laravel Controller:
$collectionArr = Collection::all()->toJson();
Then echo it out in the HTML:
<script>
var jsArray = {{$collectionArr}};
</script>
Here's more info from the Laravel Site: https://laravel.com/docs/5.3/eloquent-serialization#serializing-to-json
Upvotes: 1
Reputation: 33186
It's better to create a Laravel Collection and convert this to json so javascript can read this.
var data = {{ $products->map(function ($product) { return ['id' => $product->id , 'text' => $product->name];})->toJson() }};
It would be even cleaner to generate this json string in your controller.
Upvotes: 1