I am new to laravel livewire. I need to show multiple product quantity values from database to input field that is coming as an array. How to do this using livewire ?
Things I have tried :
Inside Livewire Component:
public $items;
public function render()
{
if (Auth::check()) {
$this->items = Cart::where('user_id', Auth::user()->id)->get();
return view('livewire.cart-page', ['cart_items' => $this->items]);
} else {
return view('livewire.cart-page');
}
}
Inside blade:
@foreach($cart_items as $cart_item)
<input class="qty-input" wire:model="product_quantity" style="border: 1px solid #d3d3d3;height: 40px;" type="number" value="{{ $cart_item->product_quantity }}" />
@endforeach
But the input field is not displaying any value. Help!
Here is my full class:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Cart;
use Illuminate\Support\Facades\Auth;
class CartPage extends Component
{
public $items;
public $product_quantity;
protected $listeners = ['cart_items' => 'get_cart_items'];
protected $rules = [
'items.*.product_quantity' => 'required',
// 'items.*.content' => 'required',
];
public function render()
{
// $cart_items = Cart::where('user_id', auth()->user()->id)->get();
// dd(Auth::id());
if (Auth::check()) {
$this->items = Cart::where('user_id', Auth::user()->id)->get();
return view('livewire.cart-page', ['cart_items' => $this->items]);
} else {
return view('livewire.cart-page');
}
// return view('livewire.cart-page', ['cart_items' => $cart_items]);
// }
}
function mount()
{
if (Auth::check()) {
$this->items = Cart::where('user_id', Auth::user()->id)->get();
}
}
public function checkout($sub_total, $cart_items)
{
// dd($sub_total);
return view('checkout', compact('sub_total', 'cart_items'));
}
public function changePrice()
{
dd("hello");
}
public function get_cart_items()
{
if (auth()->check()) {
$items = Cart::where('user_id', Auth::user()->id)->get();
return view('livewire.cart-page', ['cart_items' => $items]);
} else {
return view('livewire.cart-page');
}
}
public function delete_cart_item($id)
{
$cart = cart::find($id);
$cart->delete();
// $this->emit('cart_items');
$this->emit('count');
}
}
items array shows like this:
[![enter image description here][1]][1]
Note: this is one array. There are three more arrays similar to this. [1]: https://i.sstatic.net/mz1u0.png
public $items;topublic $cart_items;. Also this is not the best way to render things in Livewire. You should separate the DB part into themountmethod. If you share your full class I can edit and show you how.