Description:
I’m working on a Laravel project where I’m trying to display a line chart using Chart.js. I’m fetching the data from my Laravel controller and passing it to the view, but the line chart is not showing up.
Issue Details:
I have a Laravel controller method (index) where I’m fetching sales data using Eloquent and passing it to the view.
In the view (admin.index.blade.php), I’m using JavaScript to initialize Chart.js and create a line chart using the sales data.
The data is fetched correctly from the controller and passed to the view using the @json directive.
However, when I load the page, only the title “Sold Projects” is displayed, and the line chart is not visible.
Code Snippets:
Controller (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')); }
View (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
Request: Could you please help me identify why the line chart is not showing up despite having the data?