0
votes

Can I keep using a collection of custom objects throughout a Livewire lifecycle?
I create a collection, show them in a list, and take action when the user selects one.

At the moment they are still an object in the blade @foreach (i.e. {{ $item->name }}, but end up as array after the wire:click (i.e. $item['name']), which breaks running the same @foreach again after completing the wire:click method.

But more importantly, each custom object contains a collection of models and they are converted to plain array as well.

It seems this is currently expected behavior as Livewire does not know how to rehydrate them (unlike Eloquent models).

I was hoping that I could store the objects in protected property but these do not persist, just like the documentation says.

Is there a way to achieve a similar flow where I display a list (using data from custom objects) and take action on the selected custom object?

1

1 Answers

0
votes

protected properties truly are only useful for variables that are consistent, such as rules, or variables that are set each request that cannot be public.

As for the collection issue, it seems like the answer is already in the github issue thread you linked, by simply re-initiating the arrays as object. It (for now) is expected behaviour as it cannot rehydrate. You can do a map on the collection:

$this->customCollection = $this->customCollection->map(function($item) {
    return is_array($item) ? (object) $item : $item;
});

or a foreach like so:

foreach ($this->customCollection as $index => $item) {
    if (is_array($item)) {
        $this->customCollection[$index] = (object) $item;
    }
}

For each nest of collections, you'll have to do the same looping if you specifically want custom objects. It'll probably lose out on performance and you're probably better off using Eloquent collections/models or pure arrays.