I have a livewire component rendering two lists on a page. I have a button on the left list to add that item to the right list (many to many) relation using attach. This is working, but the right list isn't getting re-rendered. When I then click a filter I have on the left list, the right list re-renders showing the newly attached item. It seems like either render() isn't being called when I do the attach method, or it is taking another call to render to pick up the new relation? I also tried calling $this->render from the attach method, but that didn't help.
public function render()
{
$items = item::with('status')
->where(function($query){
$query->when(!empty($this->selectedStati), function ($query) {
$query->whereHas('status', function ($query) {
$query->whereIn('id', $this->selectedStati);
})->orWhereDoesntHave('status');
});
})
->get();
$testItems = $this->test->items;
//dd($testItems);
return view('livewire.items-source', [
'selectedStati' => $this->selectedStati,
'statuses' => $this->status,
'items' => $items,
'testItems' => $testItems
]);
}
public function filterStatus($id){
if (($key = array_search($id, $this->selectedStati)) !== false) {
unset($this->selectedStati[$key]);
} else {
$this->selectedStati[]=$id;
}
session(['status'=>$this->selectedStati]);
}
public function addToTest($id){
//attach the given item to the test
$this->test->items()->attach($id);
dd($this->test->items);
}
public function removeFromTest($id){
//detach the given item from the test
$this->test->items()->detach($id);
}
after attach the item to test collection refresh model to rehydrate it with fresh data like
public function addToTest($id){
//attach the given item to the test
$this->test->items()->attach($id);
$this->test->refresh();
}