Laravel livewire wire:model with array

Viewed 5086

From blade component I can give valule product_id

<input wire:model="qty.{{$row->product_id}}" value="{{$row->qty}}" max="{{$row->stock}}">

but how I can display qty from database and when increase qty then wire model will work and updated, what I can should do???

public $qty;
    

    public function render()
    {
        $this->userId=Auth::id();

        if ($this->qty!=null){

            foreach($this->qty as $key => $qty)
            {
                $cart=Cart::where('user_id',$this->userId)->where('product_id',$key)->first();

                if ($cart){
                    $cart->update([
                        'qty'    =>  $qty,
                    ]);
                    $this->emit('refreshCart');
                }

            }

        }

    }
1 Answers

in your blade

<input wire:model="inputs.{{ $loop->index }}.qty" value="{{$row->qty}}" max="{{$row->stock}}">
<a wire:click.prevent="increase({{$loop->index}})"></a>
<a wire:click.prevent="reduce({{$loop->index}})"></a>

in your livewire component

public $inputs = [];

    public function mount()
    {
        foreach (Cart::where('user_id',$this->userId)->get() as $item) {
            array_push($this->inputs, [
                "id" => $item->id,
                "qty" => $item->quantity,
            ]);

        }
    }
    public function reduce($index)
    {
        $product_id = $this->inputs[$index]['id'];
        $this->inputs[$index]['qty'] -= 1;
        $this->updateCart($product_id, $this->inputs[$index]['qty']);
    }
    public function increase($index)
    {
        $product_id = $this->inputs[$index]['id'];
        $this->inputs[$index]['qty'] += 1;
        $this->updateCart($product_id, $this->inputs[$index]['qty']);
    }
    public function updateCart($product_id, $productQty)
    {
        //update yourcart here with productID and qty
    }

This code works for me.

Related