Reputation: 65
I am having Item (id, code, name & price), Warehouse(id & name) and Stock (item_id, warehouse_id, stock) models where Stock model is having item_id and warehouse_id relationship keys. I am trying to fetch items from stock model using livewire mount method
public $items, $selected_id;
public function mount()
{
$this->items = Stock::select('item_id', 'warehouse_id')->groupBy('item_id', 'warehouse_id')->get();
}
and I am using this items in livewire component's select input
<select wire:model='selected_id'>
@foreach($items as $item)
<option value='{{$item->item->id}}'>{{$item->item->code}} - {{$item->item->name}} </option>
@endforech
</select>
This working perfectly fine on initial loading. but when I select a item from items select input, all items are lost and getting empty array in options.
I do not have idea on what is wrong in this code. Please help me to figure out the issue
Upvotes: 1
Views: 2154
Reputation: 398
You should only use public accessible properties for those that should be modifiable by the front-end. Keep $selected_id
as a property, but change the $items
property to a variable that you pass to the view in the render
method, or a computed property.
public $selected_id;
public function getItemsProperty()
{
return Stock::select('item_id', 'warehouse_id')->groupBy('item_id', 'warehouse_id')->get();
}
public function render()
{
return view('some-view', [
'items' => $this->items,
])
}
Disclaimer: I haven't verified this with the debugger, but this is my best guess.
Livewire serializes public properties to formats it can send to the frontend. That's why you are limited to primitives (string
, int
, array
, etc.) and some classes (Model
and Collection
). Livewire serializes Collection
and Model
under the hood to some format so that it can perform the query again in the next render, preventing stale Models
in subsequent requests.
I think this doesn't work properly, because you're using a groupBy
in your query for the $items
property.
Upvotes: 2