skip to Main Content

so i have group of components to control the quantity of each product, and each change of quantity i emit "quantityChanged" event to store in array (named ‘cart’) the product id and the new quantity. when i dump the array it shows that the array holds just the last product id and quantity, and since it shows just the last update i cant calculate the total price, but when i print it with json_encode() it shows all the elements of the array.

the quantity class:

class ProductQuantity extends Component
{
    public $product;
    public $quantity = 0;

    public function render()
    {
        return view('livewire.site.product-quantity');
    }


    public function updatedQuantity()
    {
        $this->emit('quantityChanged', $this->product->id, $this->quantity);
    }

    public function calcPrice () {
        return $this->quantity*$this->product->price;
    }
    
}

the total price class:
`

class TotalPrice extends Component
{
    public $totalPrice;
    public array $cart = [];
    protected $listeners = ["quantityChanged", "updateTotalPrice"];

    public function render()
    {
        return view('livewire.site.total-price');
    }

    public function quantityChanged($productId, $quantity)
    {
        $this->cart [$productId] = $quantity;
        dd($this->cart);
        $this->totalPrice = $this->calcTotalPrice();
    }

    public function calcTotalPrice(){
        $price = 0;
        try {
            foreach ($this->cart as $key => $quantity) {
                $price =+ Product::find($key)->price * $quantity;
            }
        } catch (Throwable $th) {
            abort(404);
        }
        return $price;
    }
}

debugger

when i dump

2

Answers


  1. In your TotalPrice class you can make selectedCartItems listner like below and listen for items being emitted from ProductQuantity component.

    class TotalPrice extends Component
    {
    
        protected $listeners = [
            'selectedCartItems'
        ];
    
    
        public function selectedCartItems($selectedCartItems)
        {
            dd($selectedCartItems);
        }
    }
    
    

    and from your ProductQuantity component you emit selectedCartItem values array directly to the TotalPrice component.

    
    class ProductQuantity extends Component
    {
        public $cartItems = [];
    
    
        public function updatedQuantity()
        {
            $this->cartItems[$productId] = $quantity;
    
            $this->emitTo('total-price', 'selectedCartItems', $this->cartItems);
        }
        
    }
    
    
    Login or Signup to reply.
  2. Check my same question here. It seems livewire has a bug when dumping arrays from the view in its functions. If you try and store it in the database or perhaps Log it instead of dumping it, you may get more favorable results.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search