使用 Laravel 和 PHP 数据的折线图未显示在 Chart.js 中

问题描述 投票:0回答:1

描述: 我正在开发一个 Laravel 项目,尝试使用 Chart.js 显示折线图。我正在从 Laravel 控制器获取数据并将其传递到视图,但折线图未显示。

问题详情:

我有一个 Laravel 控制器方法(索引),我使用 Eloquent 获取销售数据并将其传递到视图。 在视图 (admin.index.blade.php) 中,我使用 JavaScript 来初始化 Chart.js 并使用销售数据创建折线图。 使用 @json 指令从控制器正确获取数据并传递到视图。 但是,当我加载页面时,只显示标题“已售项目”,并且看不到折线图。

代码片段:

控制器(DashboardController.php):

public function index(){


$salesData = Sale::selectRaw('rf_date, SUM(total_production) as total_production')
    ->groupBy('rf_date')
    ->orderBy('rf_date')
    ->get();


// Extract the required data for the line chart using pluck
$dates = $salesData->pluck('rf_date');
$productionValues = $salesData->pluck('total_production');

return view('admin.index', compact('dates', 'productionValues')); }

查看(admin.index.blade.php):

@extends('admin.admin_master')
@section('admin')
<div class="container">
    <h1>Sold Projects</h1>
    <canvas id="soldProjectsChart" width="400" height="200"></canvas>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const dates = @json($dates);
        const productionValues = @json($productionValues);

        const canvas = document.getElementById('soldProjectsChart');
        const ctx = canvas.getContext('2d');

        const salesChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: dates,
                datasets: [{
                    label: 'Total Production',
                    data: productionValues,
                    borderColor: 'blue',
                    backgroundColor: 'lightblue',
                fill: false,
            }]
        },
        options: {
            responsive: true,
            scales: {
                x: {
                    type: 'time',
                    time: {
                        parser: 'YYYY-MM-DD',
                        unit: 'day'
                    }
                },
                y: {
                    beginAtZero: true
                }
            }
        }
    });
});
@endsection

请求:您能帮我确定为什么尽管有数据但折线图没有显示吗?

laravel chart.js
1个回答
0
投票

您的

x
规模为
type 'time'
但您没有定义任何日期库或日期适配器。时间刻度需要日期库和相应的适配器。

使用可用的 Chart.js 日期适配器之一。以下答案展示了如何使用 Luxonchartjs-adapter-luxon 来完成此操作。

https://stackoverflow.com/a/76083987/2358409

© www.soinside.com 2019 - 2024. All rights reserved.