id | title | price | sold |
---|---|---|---|
1 | Japanese Book | 150 | 55 |
2 | Flowers | 75 | 0 |
3 | Dictionary | 100 | 15 |
4 | Encyclopedia | 250 | 10 |
This is my first time doing bar chart and I'm trying to display data from my database in a bar chart but the problem I encounter is that it only displays the last data in my database which is Encyclopedia but I'm trying to display all of them. What should I change/add in my code below because I believe that my mistake is the code in my controller.
public function barChart(){
$data = product::all();
foreach($data as $data){
$prod_name = [$data->title];
$prod_sold = [$data->sold];
}
return view('bar-chart',compact('prod_name','prod_sold'));
}
Below is my code in my blade file,
<script src="https://cdnjs.com/libraries/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<div >
<canvas id="myChart" width="auto" height="100"></canvas>
</div>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: <?php echo json_encode($prod_name) ?>,
datasets: [{
label: '',
data: <?php echo json_encode($prod_sold); ?>,
backgroundColor: [
'rgba(31, 58, 147, 1)',
'rgba(37, 116, 169, 1)',
'rgba(92, 151, 191, 1)',
'rgb(200, 247, 197)',
'rgb(77, 175, 124)',
'rgb(30, 130, 76)'
],
borderColor: [
'rgba(31, 58, 147, 1)',
'rgba(37, 116, 169, 1)',
'rgba(92, 151, 191, 1)',
'rgb(200, 247, 197)',
'rgb(77, 175, 124)',
'rgb(30, 130, 76)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
max: 200,
min: 0,
ticks: {
stepSize: 50
}
}
},
plugins: {
title: {
display: false,
text: 'Custom Chart Title'
},
legend: {
display: false,
}
}
}
});
</script>
CodePudding user response:
If you want to store the data into array, you can push the data into array.
$data = product::all();
// empty array declaration
$prod_name = array();
$prod_sold = array();
foreach($data as $data){
array_push($prod_name, $data->title);
array_push($prod_sold, $data->sold);
}
To check the contents in array you can dd or echo it. Ex:
dd($prod_name);
So you can return it to bar chart with array variables
CodePudding user response:
The variables of $prod_name
and $pro_sold
are two arrays, which contain the data fetched from the database if I guess it correctly.
So, you made two mistakes.
- Assign multiple variables to a local variable
$prod_name
multiple times, so the$prod_name
only store the last variable in your loop. - As you can see, you init the variables
$prod_name
and$prod_sole
in a foreach loop, which was a bad code practice. You should init them outside the foreach function.
Check the updated code below:
public function barChart(){
$data = product::all();
// init variable
$prod_name = array();
$prod_sold = array();
foreach($data as $data){
//append a new variable to an array
$prod_name[] = $data->title;
$prod_sold[] = $data->sold;
}
return view('bar-chart',compact('prod_name','prod_sold'));
}