Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Livewire turns collection into array

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

enter image description here

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

enter image description here

How can I prevent it?

P.S.: If I put $this->products into render() function - it works ok too.

like image 470
Дмитрий Колосков Avatar asked Aug 29 '26 16:08

Дмитрий Колосков


1 Answers

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();
}
like image 74
Qirel Avatar answered Sep 03 '26 06:09

Qirel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!