Laravel/Livewire dynamic dropdown not sending the selected value

Viewed 309

Using Laravel 8 + Livewire: I was following this tutorial of creating a dynamic dropdown: https://www.itsolutionstuff.com/post/laravel-livewire-dependant-dropdown-exampleexample.html

I have this dropdown component:

public $suppliers;
    public $beans;
    public $selectedSupplier = NULL;

    public function mount()
    {
        $this->suppliers = Supplier::whereHas('greenBeans')->get();
        
        $this->beans = collect();
    }

    public function render()
    {
        return view('livewire.admin.supplier-beans-dropdown')->layout('layouts.admin.livewire');
    }  

public function updatedSelectedSupplier($supplier)
{
    if (!is_null($supplier)) {
        $this->selectedSupplier = Supplier::find($supplier);
        $this->beans = $this->selectedSupplier->greenBeans;
    }
}

The component's blade:

<div>
<div class="form-group">
    <label for="supplier" class="col-md-4 form-label">Supplier</label>
    <select wire:model.lazy="selectedSupplier" class="form-control">
        <option value="" selected>Select Supplier</option>
        @foreach($suppliers as $supplier)
            <option value="{{ $supplier->id }}">{{ $supplier->name }}</option>
        @endforeach
    </select>        
</div>

@if (!is_null($selectedSupplier))
    <div class="form-group">
        <label for="bean" class="form-label">Green Bean</label>
        <select class="form-control" name="bean" wire:model.lazy="selectedBean">
            <option value="" selected>Select Green Bean...</option>
                @foreach($beans as $bean)
                    <option value="{{ $bean->id }}">{{ $bean->name }}</option>
                @endforeach
        </select>
    </div>
@endif

I have an other component that needs to call this dropdown. So in this parent component I have this var: $selectedSupplier and in the view I call the dropdown component:

@livewire('admin.supplier-beans-dropdown')

When I select a supplier and submit the form, the selectedSupplier is null.

So how do I use this dropdown in different components? How do I send the selected value to the parent component?

1 Answers

check this first I think you have some errors here. you have:

public function updatedSelectedSupplier($supplier)
{
  if (!is_null($supplier)) {
    $this->supplier = Supplier::find(supplier); --> typo error here???
    $this->beans = $supplier->greenBeans; --> $supplier parameter is an ID???
  }
} 

and I think it should be:

if (!is_null($supplier)) {
    $this->supplier = Supplier::find($supplier); 
    $this->beans = $this->supplier->greenBeans;
}
Related