Variable blank after first request?

Hi, I have a search dropdown which allows a user (amongst other things) to pick a country from a dropdown list.

This aspect of the component is not dynamic, so I am selecting the data in a standard Laravel Controller, and then passing it to the component using:

@livewire('search-dropdown', ['countries' => $countries])

In SearchDropdown.php (Livewire component) I initalize the data using the following:

public function mount($countries) {
    $this->countries = $countries;
}

This works successfully for the initial page load and the list of countries is displayed in a list in the view as expected. However, when the component refreshes, the list of countries appears blank.

The strangest thing is that I can see the data is being successfully sent from Livewire to the view on subsequent requests, but it doesn’t display in the view?

I’m really confused as it seems as though this should work, and the data is being correctly sent for all requests? For reference, I am displaying the data in the view using the following:

@foreach ($countries as $country)
      @if(!empty($country->country_name)) <option>{{ $country->country_name }}</option> @endif
@endforeach

Any ideas? Any help appreciated!

Okay so this is WEIRD.

I was able to fix it by using:

@foreach ($countries as $country)
    @if(empty($country->country_name))
            <option>{{ $country['country_name'] }}</option>
        @else
            <option>{{ $country->country_name }}</option>
        @endif
@endforeach

For some reason, it appears the initial request is a stdClass object, so we access it via:
->country_name then, subsequent requests are an array, so we use ['country_name']

This feels extremely dirty so if you can see what’s happening please let me know!

That’s really weird. Are you feeding the component differently? Can you post your component code and some contextual code on how you’re using the component in your view? That could help whittle down the issue.

Livewire cannot roundtrip Eloquent models. If you want to use object references in the view then you should renew the list in the render method each time.

Other tips here

http://novate.co.uk/dynamic-cascading-dropdown-with-livewire/

Extending @Snapey, you can make your life easier by converting it to an array to start with so you don’t have conditional checks in your view, or depending on how the countries list is generated from the beginning, you can cast it to a collection.