简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM