user6253429
user6253429

Reputation:

Push Laravel collection in a javascript array

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

Answers (3)

apokryfos
apokryfos

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

Aaron Dressler
Aaron Dressler

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

Jerodev
Jerodev

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

Related Questions