So i'm super new to livewire and developing overall so following the series on laracasts with some edits and can't make things work. I'm trying to create a simple list of items that have been selected from a catalog, i've taken the search dropdown from laracast example and trying to have the view show items selected using the wire:click action.
Whenever i select an item i get "ErrorException array_push() expects parameter 1 to be array, null given". I can put the $addToList = []; into the selectitem function but then it clears each time the wire:click fires (at 2nd item added).
i feel i'm missing something simple but am completely stuck.
use App\Models\Catalog;
use Livewire\Component;
class DropdownExample extends Component
{
public $search;
public $searchResults = [];
public $selectedItems = [];
public $addToList = [];
public function selectItem(Catalog $item)
{
array_push($addToList, $item);
$this->selectedItems = $addToList;
}
public function updatedSearch($newValue)
{
if (strlen($this->search) < 3) {
$this->searchResults = [];
return;
}
$items = Catalog::where('title', 'like', '%' . $this->search . '%')->get();
$this->searchResults = $items;
}
public function render()
{
return view('livewire.dropdown-example');
}
}
livewire view:
@if (strlen($search) > 2)
<ul>
@foreach ($searchResults as $result)
<li>
<span wire:click="selectItem({{ $result->id }})">
{{ $result->title }}
</span>
</li>
@endforeach
</ul>
@endif
<div class="mt-2 bg-blue-300">
<ul>
@foreach ($selectedItems as $item)
<li>{{ $item->title }}</li>
@endforeach
</ul>
</div>