Livewire

Building a Shopping Cart with Livewire v4

February 01, 2026 1 min read 19 views

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
Share this post:

Related Posts

Comments (0)

Please log in to leave a comment. Log in

No comments yet. Be the first to comment!