Laravel Livewire, adding Input field (type=text) when chosing Other

  html, laravel, laravel-livewire, php

Laravel Livewire project. Created a dynamic form with conditional fields. Need to add input field type=text when choosing the business type after choosing the business kind ( online/ physical). I’ve asked on many forums, people gave several instrustrions but Im finding it kinda difficult since Im not quite experienced when it comes to php.


namespace AppHttpLivewire;

use AppModelsClasses;
use AppModelsSection;
use LivewireComponent;

class Conditional extends Component
{
    public $parents = [];
    public $children = [];

    public function mount()
    {
        $this->parents = [
            ['id' => -1, 'title' => 'Select type'],
            ['id' => 1, 'title' => 'Physical Store'],
            ['id' => 2, 'title' => 'Online Shop'],
        ];
    }

    public function onSelectFirst($option)
    {
        switch($option) {
            case '-1': {
                $this->children = [];
                break;
            }

            case '1': {
                $this->children = [
                    ['id' => -1, 'title' => 'Please select'],
                    ['id' => 1, 'title' => 'Restaurant'],
                    ['id' => 2, 'title' => 'Fast Food'],
                    ['id' => 3, 'title' => 'Cafe'],
                    ['id' => 4, 'title' => 'Bar'],
                    ['id' => 5, 'title' => 'Night club'],
                    ['id' => 6, 'title' => 'Other'], // here
                ];

                break;
            }

            case '2': {
                $this->children = [
                    ['id' => -1, 'title' => 'Please select'],
                    ['id' => 7, 'title' => 'Clothes'],
                    ['id' => 8, 'title' => 'Food Delivery'],
                    ['id' => 9, 'title' => 'Other'], // here
                ];

                break;
            }
        }
    }

    public function render()
    {
        return view('livewire.conditional');
    }
}
  <x-jet-label for="business_kind" value="{{ ('Type')}}" />
    <select name="business_kind" id="business_kind" wire:click="onSelectFirst($event.target.value)" wire:change="onSelectFirst($event.target.value)">
      @foreach($parents as $option)
        <option value="{{ $option['id'] }}">{{ $option['title'] }}</option>
      @endforeach
    </select>
  <x-jet-label for="business_type" value="{{ ('Business type')}}"/>
    <select id="business_type" name="business_type" wire:loading.attr="disabled"'>
      @foreach($children as $option)
        <option value="{{ $option['id'] }}">{{ $option['title'] }}</option>
      @endforeach
  </select>
</div>

Source: Laravel

Leave a Reply