I’m working on a simple component that displays all related items on an order. I’m using a nested component. In the end I’d like to change the data in the nested component.
I have the following models:
Order - columns: id
OrderItem - columns: id, article_name, order_id
There is an $order
variable available in the page controller. This is either an existing Order
or an empty one, initiated with new Order()
. Order
has a relation set up to OrderItem
's.
The $order
is handed to the Livewire component:
@livewire('order.overview', ['order' => $order])
The contents of the Component’s class are:
<?php
namespace App\Http\Livewire\Order;
use App\Order;
use Livewire\Component;
class Overview extends Component
{
public $order;
public $items = [];
public function addItem()
{
}
public function mount(Order $order)
{
$this->order = $order;
$this->items = $this->getItemsFromOrder($order);
}
public function render()
{
return view('livewire.order.overview');
}
public function getItemsFromOrder($order)
{
if (!$order || !$order->exists) {
return [[
'id' => 0,
'order_id' => 0,
'article_name' => '',
]];
}
return $order->items->toArray();
}
}
I’ve left addItem()
empty for now. I know this doesn’t do anything right now.
I’ve also made a very basic view, it lists all $items
as specified in the Overview
class and there is a button that’s supposed to trigger addItem()
.
<div>
@foreach ($items as $item)
@livewire('order.item', ['item' => $item], key($item['id']))
@endforeach
<button wire:click="addItem" class="border border-green-900 p-2 mt-4">Add row</button>
</div>
All of this works without errors if $this->order
exists.
If the order doesn’t exist and I pass an empty Order
model, I get a 404 when addItem
is supposed to run. It returns:
No query results for model [App\Order].
I don’t get that. Why would it run a query against it? mount()
should only run once unless I’m misunderstanding the lifecycle hooks. If I remove $this->order = $order
from mount()
there are no errors but I’d like to use the order in addItem()
.
I must be missing something