I have a public property which is an eloquent models collection. I’m trying to add some temporary attributes to the models.
However, when refreshing the component, these attributes are lost.
Is there any way to preserve them?
Adding code example and a couple of comments regarding the ‘quantity’ property, which is not actually defined in the model, but a temporary attribute. Same for the ‘total’ attribute.
class OrderTable extends Component
{
public $items;
protected $listeners = ['itemAdded' => 'incrementItem'];
public function render()
{
return view('livewire.sales-orders.order-table', [
'items' => $this->items
]);
}
public function mount()
{
$this->items = Collection::make();
}
public function incrementItem($item_id)
{
$itemExists = false;
if ($this->items->contains('id', $item_id)) {
$itemExists = true;
$item = $this->items->firstWhere('id', $item_id);
// When getting here, the dynamic 'quantity' attribute is null.
$item->quantity = $item->quantity + 1;
} else {
$item = Item::findOrFail($item_id);
$item->quantity = 1; // Adding dynamic 'quantity' here
}
$item->total = $item->quantity * $item->cost;
if (!$itemExists) {
$this->items->push($item);
}
}
}