NateRoberts's avatar

Array not working in livewire component

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>
0 likes
1 reply
MarianoMoreyra's avatar
Level 25

Hi @nvkodde

Why do you have 2 arrays ($selectedItems and $addToList) to hold the same information?

At first glance, I understand that you only need $selectedItems, in which case you could try changing the selectItem method to this:

public function selectItem(Catalog $item)
{
	array_push($this->selectedItems, $item); 
}

Note that in your original code, the array_push error was happening because you missed the $this-> to access the $addToList array.

Hope this works for you!

Please or to participate in this conversation.