skip to Main Content

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.

2

Answers


  1. When you add a item to the Cart, you need to send a event to Counter component:

    In Counter, you need to listen to Counter event

    class Counter extends Component
    {
    
        public $counter = '';
        protected $listeners = ['counter'];
    
    
        public function counter()
        {
    
            $cartCollection = Cart::getContent();
    
            $this->counter = $cartCollection->count();
          
        }
    }
    

    Then:

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

    Reference https://laravel-livewire.com/docs/2.x/events

    Login or Signup to reply.
  2. where u calling function counter()? maybe call on render method like this

    public function render()
    {
        $this->counter();
     
        return view('livewire.contadorpedido');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search