[SOLVED] Laravel how to pass data into Chart.js?


This Content is from Stack Overflow. Question asked by Wesley

I want to pass data into Chart.js, however nothing appear on the card. How to solve this problem adn what is the correct way to pass data into Chart.js? I cant directly put the data into the script in this way.


public function ViewAnalytic(){

        $id = Auth::user()->id;
        $electrical = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Electrical System')->count();
        $pest = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Plumbing System')->count();
        $plumbing = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Pest Infectations')->count();
        $structural = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Structural Repairs')->count();
        $appliances = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Electrical Appliances')->count();
        $others = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Others')->count();

        return view('analytic.analytic-page', compact('total_num', 'vacant', 'rented', 'user', 'paid', 'unpaid', 
        'electrical', 'pest', 'plumbing', 'structural', 'appliances', 'others'));


<div class="card-body px-3 py-4-5">
    <canvas id="myChart" width="200" height="200"></canvas>


        const data = {
        labels: [
            'Electrical System',
            'Plumbing System',
            'Pest Infections',
            'Structural Repairs',
            'Electrical Appliances',
        datasets: [{
            label: 'My First Dataset',
            data: [{!!$electrical!!}, {!!$plumbing!!}g, {!!$pest!!}, {!!$structural!!}, {!!$appliances!!}, {!!$others!!}],
            backgroundColor: [
            'rgb(255, 99, 132)',
            'rgb(204, 102, 235)',
            'rgb(255, 205, 86)',
            'rgb(0, 204, 102)',
            'rgb(102, 153, 255)',
            'rgb(191, 0, 205)'
            hoverOffset: 4
        const ctx = document.getElementById('myChart').getContext('2d');
        const myChart = new Chart(ctx, {
            type: 'pie',
            data: data,


Make an ajax request in the view file, then push the values in the chart.
And you can try this

{!! json_encode($electrical) !!}

Have a look at this tutorial


This Question was asked in StackOverflow by Wesley and Answered by Sajid 285 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?