Reputation: 69
In mount()
function of livewire component I have a collection, whick looks like this:
$this->products = $purchase->getProductsList();
getProductsList()
is a function of Purchase model:
public function getProductsList() : Collection
{
$products = $this->purchaseSkus->pluck('sku.product')->unique();
return $products;
}
Whenever component's blade is rendered - it works ok
But in the same blade I have a textarea with wire:model="description"
and function updatedDescription()
in component. And after making changes in textarea $products
turns into array
How can I prevent it?
P.S.: If I put $this->products
into render()
function - it works ok too.
Upvotes: 6
Views: 6248
Reputation: 26450
There are two different collections in Laravel, the "default" one Illuminate\Support\Collection
- and an additional one for Eloquent collections, Illuminate\Database\Eloquent\Collection
. You should be using the second one - as Livewire will better know how to serialize/unserialize an Eloquent-collection of models with this.
pluck()
returns an instance of Illuminate\Support\Collection
- which Livewire will hydrate as an array. Anything that isn't a Model or an Eloquent Collection, will be hydrated as an array (aside from non-iterable objects like strings, intergers, booleans, etc).
To fix this, you can get the data via the Product model, something like this. Since I've not seen the actual relations, or what $this->purchaseSkus
is, this is somewhat pseudo-code, and you should fix the relation sku.purchase
to what it actually is. This gets all products where there is a relation to the data in $this->purchaseSkus
.
public function getProductsList() : Illuminate\Database\Eloquent\Collection
{
return Product::whereHas('sku.purchase', function($query) {
return $query->whereIn('id', $this->purchaseSkus->puck('id'));
})
->distinct()
->get();
}
Upvotes: 15