【问题标题】:Laravel how to pass data into Chart.js?Laravel如何将数据传递到Chart.js?
【发布时间】:2022-09-24 01:08:15
【问题描述】:

我想将数据传递到 Chart.js,但是卡片上什么也没有。如何解决这个问题以及将数据传递到 Chart.js 的正确方法是什么?我不能用这种方式直接将数据放入脚本中。

控制器

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

view.blade.php

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

脚本

   <script>
        const data = {
        labels: [
            \'Electrical System\',
            \'Plumbing System\',
            \'Pest Infections\',
            \'Structural Repairs\',
            \'Electrical Appliances\',
            \'Others\'
        ],
        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,
        });
    </script>

    标签: laravel chart.js laravel-9


    【解决方案1】:

    在视图文件中发出 ajax 请求,然后将值推送到图表中。 你可以试试这个

    {!! json_encode($electrical) !!}

    看看这个教程

    https://www.codeleaks.io/ajax-get-post-request-in-laravel/

    【讨论】:

    猜你喜欢
    • 2021-02-28
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多