Build a shopping cart with Livewire.
Cart Component
@php
new class extends Livewire\Component {
public array $items = [];
public function addItem(int $productId): void
{
$product = Product::find($productId);
$this->items[$productId] = [
'name' => $product->name,
'price' => $product->price,
'qty' => ($this->items[$productId]['qty'] ?? 0) + 1,
];
}
#[Computed]
public function total(): float
{
return collect($this->items)->sum(fn($i) => $i['price'] * $i['qty']);
}
}
@endphp