Search code examples
laravellaravel-8laravel-livewire

Laravel Livewire: Passing option value onChange of Select input


I am trying to pass a value from the <option> of my <select> input to my livewire controller component and echo the value.

Livewire Blade View Component:

{!! Form::select('goals',$goals_plucked,null,[
    'placeholder' => trans('classes.backend.forms.select_goals'),
    'class' => 'custom-select',
    'id' => 'goals',
    'wire:change' => "goals(this.val)",
]) !!}

This get's me an output of null in my Livewire Controller Component

Livewire Controller Component

public $goals;

public function goals($goals)
{
    dd($goals);
}

After watching some tutorials. I also tried using 'wire:change' => "goals($event.target.value)", which gave me an error of Undefined variable $event, obviously because it was not defined in main controller. I am not sure what am I doing wrong here.

What I am trying to do: Trying to create a flow just like select country then select state and then select city. via livewire. Before selecting a country the inputs of the select state and city won't be visible


Solution

  • I tried below code and it worked for me well. Just had to make sure I use normal html form inputs and dynamically add options to it by foreach loop. Also used mount() function for getting getting values and id's for select dropdowns.

    Livewire Blade View Component:

    <select wire:model="goal" name="goal" class="form-control" required>
        <option value="">
            {!! trans('classes.backend.forms.select_goals') !!}
        </option>
        @foreach ($goals as $goal)
            <option value="{{ $goal->id }}">{{ $goal->goals }}</option>
        @endforeach
    </select>
    

    Livewire controller component

    public $goals;
    public $goal;
    
    public function mount()
    {
        $this->goals = Goals::all()->isActive();
    }
    
    public function updatedGoal($value)
    {
        dd($value);
    }