Hello,
I have followed the Laravel Cookbook two first videos by Andre Madarang and I don't understand why my code doesn't work as expected.
Here is my Livewire class.
<?php
namespace App\Livewire\Charts;
use App\Models\Sale;
use App\Models\Article;
use App\Models\Product;
use Livewire\Component;
use App\Models\SalesView;
use Illuminate\Support\Carbon;
class SalesAmountChart extends Component
{
public $chart;
public $years;
public $selectedYear;
public $months;
public function mount()
{
$now = Carbon::now();
$this->selectedYear = (int) $now->format('Y');
$this->months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
$this->years = SalesView::distinct()->orderBy('year')->pluck('year')->toArray();
$this->setChartDatas();
}
public function updatedSelectedYear()
{
$this->setChartDatas();
$this->dispatch('chart-datas-updated');
}
private function setChartDatas()
{
$sales_amount_per_month = SalesView::
where('year', $this->selectedYear)
->orderBy('month')
->get()
->pluck('sales_amount')
->toArray();
$datasets[] = [
'label' => 'Monthly sales amount',
'data' => $sales_amount_per_month,
];
$this->chart = [
'config' => [
'type' => 'bar',
'data' => [
'datasets' => $datasets,
'labels' => $this->months,
],
'options' => [
'responsive' => true,
'maintainAspectRatio' => false,
],
],
];
}
public function render()
{
return view('livewire.charts.sales-amount-chart');
}
}
And here my Livewire blade view.
<section
wire:ignore
class="w-full space-y-4"
x-data="{
chart: $wire.entangle('chart'),
init() {
const chart = new Chart(this.$refs.chart, this.chart.config);
Livewire.on('chart-datas-updated', () => {
chart.data.datasets[0].data = this.chart.config.data.datasets[0].data;
chart.update();
});
},
}"
>
<div class="w-full bg-white rounded-lg px-3 py-2">
<select
wire:model.live="selectedYear"
class="transition-all outline-none px-3 py-2 rounded-full bg-gray-300 text-black"
>
@foreach ($years as $year)
<option value="{{ $year }}">{{ $year }}</option>
@endforeach
</select>
<article class="relative w-full h-80">
<canvas x-ref="chart"></canvas>
</article>
</div>
</section>
When I load the component, it works fine, the chart is correctly displayed with 2025 datas.
Then I select 2024 with the select / options field and nothing happens.
I come back to 2025 and the chart changes with the 2024 datas.
I change the year to 2024 and the chart changes with the 2025 datas.
I thought it was due to entangle and I have tried to add .live to chart: $wire.entangle('chart').live, but it doesn't work better.
I have checked with some dd() in the class, the $chart variable is correcty updated with the right datas. So the problem seems to come from the synchronization of the datas between Livewire and AlpineJS.
What happens ?
Can you help me please ?
Thanks a lot ;).
V