the incrementQuantity function not being called in your Livewire component could be due to Missing @livewireScripts in Blade Template, also In your Blade code, you've defined the button as type="button". This prevents form submission, which might be what you want. However, if you intended the click event to trigger form submission, change it to type="submit". See if that helps
Jul 31, 2024
2
Level 1
Function is not calling in livewire:click
When I try to increment/decrement the quantity nothing happens. My livewire component code below, class CartComponent extends Component { public $cartItems; public function mount() { $this->fetchCartItems(); }
public function fetchCartItems()
{
$this->cartItems = Cart::where('user_id', Auth::id())->get();
}
public function incrementQuantity($cartId)
{
$cartItem = Cart::where('user_id', Auth::id())
->where('id', $cartId)
->first();
if ($cartItem) {
$cartItem->increment('quantity');
$this->fetchCartItems();
$this->dispatchBrowserEvent('message',[
'text' => 'Quantity updated',
'type' => 'success',
'status' => 200
]);
} else {
$this->dispatchBrowserEvent('message',[
'text' => 'Something went wrong',
'type' => 'error',
'status' => 404
]);
}
}
public function decrementQuantity($cartId)
{
$cartItem = Cart::where('user_id', Auth::id())
->where('id', $cartId)
->first();
if ($cartItem && $cartItem->quantity > 1) {
$cartItem->decrement('quantity');
$this->fetchCartItems();
$this->dispatchBrowserEvent('message',[
'text' => 'Quantity updated',
'type' => 'success',
'status' => 200
]);
} else {
$this->dispatchBrowserEvent('message',[
'text' => 'Something went wrong',
'type' => 'error',
'status' => 404
]);
}
}
public function removeItem($cartId)
{
$cartItem = Cart::where('user_id', Auth::id())
->where('id', $cartId)
->first();
if ($cartItem) {
$cartItem->delete();
$this->fetchCartItems();
$this->dispatchBrowserEvent('message',[
'text' => 'Item removed from cart',
'type' => 'success',
'status' => 200
]);
} else {
$this->dispatchBrowserEvent('message',[
'text' => 'Something went wrong',
'type' => 'error',
'status' => 404
]);
}
}
public function render()
{
return view('livewire.cart', [
'cartItems' => $this->cartItems,
])->extends('layouts.app');
}
}
My Blade file code is below
<span>{{ $item->quantity}}</span>
<button type="button" wire:click="incrementQuantity({{ $item->id }})" wire:loading.attr="disabled">
<svg class="w-3 h-3" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="100"
height="100" viewBox="0 0 24 24">
<path fill-rule="evenodd"
d="M 11 2 L 11 11 L 2 11 L 2 13 L 11 13 L 11 22 L 13 22 L 13 13 L 22 13 L 22 11 L 13 11 L 13 2 Z">
</path>
</svg>
</button>
</div>
{{-- <div wire:loading wire:target="incrementQuantity, decrementQuantity" class="text-gray-500">Updating...</div> --}}
</div>
What I checked already,
- Livewire script in app.blade
- Livewire working in another test file , So no point in livewire configuration.
Please or to participate in this conversation.