I try to get some chart with chart.js with data from a database.
If I put it directly inside the array its works fine, if i try to bind it inside a foreach loop I get "the variable $subs" is assigned, but never been used and there is no chart inside the view.
My Component :
<?php
namespace App\Livewire\Charts;
use Livewire\Component;
use App\Models\wine;
use App\Models\Grape;
use App\Models\WineGrape;
class GrapeCharts extends Component
{
public $wines;
public $values;
public $grape;
public $subs = [];
//public $subs = [
// ['Grape' => 'Grenache', 'Value' => 75],
// ['Grape' => 'Syrah', 'Value' => 25],
//]; ->> This works as intended
public function mount($wine_id)
{
$this->wines = Wine::where('id', '=', $wine_id)->first();
$this->values = WineGrape::where('wine_id', '=', $wine_id)->get();
foreach ($this->values as $value) {
$this->grape = Grape::where('id', '=', $value->grape_id)->first();
$subs = [
['Grape' => $this->grape->grapename, 'Value' => $value->amount],
];
}
}
public function render()
{
return view('livewire.charts.grape-charts');
}
}
My View :
<style type="text/css">
.ChartBox {
height: 600px;
}
</style>
<div class="row">
<div class="ChartBox col-6" wire:ignore>
<canvas id="myChart"></canvas>
</div>
</div>
@assets <script type="text/javascript" src="{{ asset('assets/js/chart.min.js') }}"></script>@endassets
@script <script>
const ctx=document.getElementById('myChart');
// const ctx2=document.getElementById('myChart2');
const subs=$wire.subs;
const Labels=subs.map(item=>item.Grape);
const values=subs.map(item=>item.Value);
new Chart(ctx, {
type: 'pie',
data: {
labels: Labels,
datasets: [ {
label: '%',
data: values,
borderWidth: 1
}
]
}
,
options: {
responsive: true
}
});
</script>
@endscript
It seems as if the variable $subs is not getting to the view. What is the correct way to bind the data and get it to the view ?