Home > database >  Assign array of objects from controller to JS in blade in Laravel
Assign array of objects from controller to JS in blade in Laravel

Time:11-21

I have an array of object as follows Array ( [0] => stdClass Object ( [id] => 14 [content] => সংবাদ [start] => 2022-10-17 00:00:00 ) [1] => stdClass Object ( [id] => 15 [content] => সংবাদ [start] => 2022-10-17 00:00:00 ) [2] => stdClass Object ( [id] => 11 [content] => সংবাদ [start] => 2022-09-28 00:00:00 ) [3] => stdClass Object ( [id] => 12 [content] => সংবাদ [start] => 2022-09-28 00:00:00 ) [4] => stdClass Object ( [id] => 1 [content] => সংবাদ [start] => 2022-09-27 00:00:00 ) )

Which i have passed from controller and want to assign in the script in the blade file. the final js should look like this

var items = new vis.DataSet([
    {id: 1, content: 'item 1', start: '2014-04-20'},
    {id: 2, content: 'item 2', start: '2014-04-14'},
    {id: 3, content: 'item 3', start: '2014-04-18'},
  ]);

I tried this.

var items = new vis.DataSet({{$timeline}});

But it is throuhing an error

htmlspecialchars(): Argument #1 ($string) must be of type string, array given

What i am missing. please help. Thanks

CodePudding user response:

As per your error use: {!! $timeline !!} this forces Blade to not escape the value passed. May be worth encoding the timeline and decoding in JS.

CodePudding user response:

you just need to json encode it before echoing it.

var items = new vis.DataSet(@json($timeline));

or

var items = new vis.DataSet({!! json_encode($timeline) !!});
  • Related