[Chartjs]-Charts js and laravel: Render chart after passing in json data

2👍

It seems you are doing json_encode() twice. In the controller and in the scripts. Call json_encode() in the controller and then in the script do

data: {{ $revenue }},

Or

data: <?php echo $revenue; ?>,

$revenue is undefined because you pass it a session variable using with(). Instead return it to your view like this:

$revenue = Invoice::all()->pluck('amount')->tojson();
return view('home', compact('revenue')); //'revenue' will match $revenue

1👍

I don’t know about the chart thing but you are encoding your data 3 times!!!

public function chartjs()
{    
    $revenue = Invoice::all()->pluck('amount')->toJson();
    // $revenue is already a json string
    return view('home')
        ->with('revenue',$revenue); // you don't need this json_encode
}

Also in your view you don’t need the json_encode. You also might need to put the json string inside quotation.

 data: @'{{$revenue}}',

1👍

It seems like you’re calling json_encode more than once. The tojson() must be enough.

Your return could be like this

return view('home', [ 'revenue' => $revenue ]);

And then print it on javascript like this:

data: {!! $revenue !!}

Also check if the data structure printed in your HTML source code is equivalent to the one required by the chart library.

Leave a comment