Skip to content

Instantly share code, notes, and snippets.

@Neeraj1005
Created March 8, 2021 12:43
Show Gist options
  • Save Neeraj1005/a1b341786d6de48e913c5f48b6c49e9c to your computer and use it in GitHub Desktop.
Save Neeraj1005/a1b341786d6de48e913c5f48b6c49e9c to your computer and use it in GitHub Desktop.
descendent dropdown for country and state Using Livewire

In this I have done descendent dropdown using Laravel Livewire

Country Component

<?php

namespace App\Http\Livewire\Company;

use App\Tbl_accounttypes;
use App\Tbl_countries;
use App\Tbl_industrytypes;
use App\Tbl_states;
use Livewire\Component;

class SubmitCompanyForm extends Component
{
    public $country_id;
    public $state_id;
    
    // descendent dropdown
    public $countries;
    public $states = []; // after selecting the country_id the data will be formed in array

    protected $rules = [
        'country_id' => 'required|not_in:0',
        'state_id' => 'required|not_in:0',
    ];

    public function store()
    {
        $data = $this->validate();

        dd($data);
    }

    public function render()
    {
        $this->countries = Tbl_countries::get();
        if (!empty($this->country_id)) {
            $this->states = Tbl_states::where('country_id',$this->country_id)->get();
        }

        return view('livewire.company.submit-company-form');
    }
}

livewire-blade file

 <div class="form-group row">
      <label class="col-md-3 col-form-label text-right" for="country_id">Country</label>
      <div class="col-md-9">
          <select wire:model="country_id" class="form-control required" name="country_id"
              id="country_id">
              <option value="0">select country</option>
              @foreach ($countries as $country)
                  <option value="{{ $country->id }}">{{ $country->name }}</option>
              @endforeach
          </select>
          @error('country_id') <span class="text-danger">{{ $message }}</span> @enderror
      </div>

  </div>


<div class="form-group row">
    <label class="col-md-3 col-form-label text-right" for="state_id">State</label>
    <div class="col-md-9">
        <select wire:model="state_id" class="form-control required" name="state_id"
            id="state_id">
            <option value="0">Select State</option>
            @foreach ($states as $state)
                <option value="{{ $state->id }}">{{ $state->name }}</option>
            @endforeach
        </select>
        @error('state_id') <span class="text-danger">{{ $message }}</span> @enderror
    </div>

</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment