【发布时间】: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