I have a Livewire component with the following properties...
class MyClass extends Livewire\Component {
public $dataCollection; // instance of Illuminate\Database\Eloquent\Collection
public $dataArray; // converted to an array of arrays
/* ... blah ... */
function getData() {
/* ... */
$this->dataCollection = $ordersModel->processMySearch($srch)->get(); // returns multiple lines of data, producing a Collection
$this->dataArray = $this->dataCollection->toArray();
}
}
Now, my objective is push this data to the Livewire/Blade template and entangle it with an AlpineJS variable.
<div x-data="{
myCollection: @entangle('dataCollection').defer,
myArray: @entangle('dataArray').defer
}">
<table>
<tbody>
<template x-for="myRow in myCollection">
<tr>
<template x-for="(myData, colName) in myRow">
<td :class="colName" x-text="myData"></td>
</template>
</tr>
</template>
</tbody>
</table>
</div>
It doesn't work, because it seems that the collection of models doesn't convert (or map) properly from Livewire/PHP into the Alpine myCollection variable. When I run a console.log() debug on the variable, it tells me that it's an empty array.
However, if I loop the table the myArray variable (rather than the myCollection one):
<table>
<tbody>
<template x-for="myRow in myArray">
<tr>
<!-- etc -->
Then the HTML table generates on page nicely.
The reason I would prefer to use the Collection object, is because I may want to update some of the data in the table. If I am able to update the data in the (@entangleed) Model objects and have the Models synch back to the Livewire/PHP component, then I won't need to re-generate the models in PHP, potentially saving me some database calls.
Is it possible to @entangle Alpine variables to PHP Collections in this way? If so, what am I doing wrong and why isn't it working in the above example?
x
Disclaimer The above code is a (very) simplified excerpt of a larger project that I'm working on. It's not a direct copy/paste of the original code and as such may contain minor syntax errors. Please treat it as pseudo code.