0

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.