Search code examples
laravellaravel-livewire

real time counter with livewire


i am new with livewire. I try to make a counter in real time, the counter shows the amount of products in the user's cart

  class Counter extends Component
{

    public $counter = '';
    
    public function render()
    {
          
     
        return view('livewire.contadorpedido');
    }


    public function counter()
    {

        $cartCollection = Cart::getContent();

        $this->counter = $cartCollection->count();
      
    }
}

Blade:

 <div>
    
    {{$counter}}
  
 
</div>

method to add products:

   \Cart::add([
            'id' => $product->id,
            'name' => $product->nombre,
            'price' => $product->precio,
            'quantity' => 1,
            'attributes' => array(
                'image' => $product->imagen,
            )
        ]);

The problem is that in the view it does not show me any value. Adding products does not update or show the counter number either.


Solution

  • where u calling function counter()? maybe call on render method like this

    public function render()
    {
        $this->counter();
     
        return view('livewire.contadorpedido');
    }