John Davidson

php - Livewire add an quantity input for each row

0 comments
Message:


I am trying to add a product to my cart from a list of products. I am using Laravel Livewire. With the code below I am managing to add each product where I click order to the cart (which is just a session variable). Now, I am trying to add an quantity input so that for each product I can choose an amount of products to add to my cart.


Bear in mind from my code below that Products is an eloquent collection and in that collection I don't have a property quantity. To my opinion this is also not needed as the quantity is not part of the product model but rather something that belongs to my cart.


So below is my the Livewire php part.


class Dashboard extends Component
{
use WithPagination;

public string $search = '';

public function render(): View
{
return view('welcome', [
'products' => Product::search('description', $this->search)->paginate(9)
])->layout('layouts.app');
}

public function addToCart(int $productId)
{
Cart::add(Product::where('id', $productId)->first());
}

}

And this is the blade part:


 @foreach($products as $product)
<x-table.row wire:loading.class.delay="opacity-50" wire:key="{{ $product->id }}">
<x-table.cell>{{ $product->description }}</x-table.cell>
<x-table.cell> &euro;{{ number_format($product->price, 2) }}</x-table.cell>
<x-table.cell>
<input type="number"name="quanity" class="w-16 mx-8" />
<button wire:click="addToCart({{$product->id}})">Order</button>
</x-table.cell>
</x-table.row>
@endforeach


I would think the best option is to add a second parameter to the addToCart function which is the quantity. But I can't make that work.


Suggestions are very welcome.


Thanks.



My Answer:
Product::where('name', 'like', '%' . $this->search . '%')->paginate(10), ]); }__ public function addToCart($productId) {_ $cart = session('cart', []); $cart[$productId] = $cart[$productId] + 1 ?? 1; session(['cart' => $cart]); }_}

Rate this post

3 of 5 based on 2847 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us