Creating Dynamic Select (Drop Down Input) with Laravel 5

There are times that you want to populate your input select based on another input selection. For instance, in State-City relationship where State has many City. So each State has its own City to address with. In your select input you don't want to display all Cities to a State that has no relation to it.

What we want is to repopulate the City input select based on the State selection. So that when you select a State only those Cities under that State will be display.

Now lets go with the Steps.


First Step: The Select Input in View

<div class="form-group">

    <label>State

        <select name="state" id="state" class="form-control input-sm">

            <option value=""></option>

            @foreach($states as $state)

                <option value="{{ $state->id }}">{{ $state->name}}</option>

            @endforeach

        </select>

    </label>

</div>

<div class="form-group">

    <label>City

        <select name="city_id" id="city" class="form-control input-sm">

            <option value=""></option>

        </select>

    </label>

</div>



We created an Input Select in a form. We loop through the passed variable $states from the controller which display all states name. The second Input will be for our City to be populated by javascript. Make sure you have the right ID's for each input.



Second Step: The Route.
use App\City;



Route::get('/information/create/ajax-state',function(){

    $state_id = Input::get('state_id');



    $subcategories = City::where('state_id','=',$state_id)->get();



    return Response::json($subcategories);

});


Make sure to use the model for the City.


What happens here is that we created a route that will get the list of Cities based on the State Input. This route will trigger only by an Ajax script in the view. The data that it produce will be passed as Json, that can be captured by our Ajax.



Third Step: The JavaScript
<script>

    $('#state').on('change', function(e){

        console.log(e);



        var state_id = e.target.value;



        $.get('{{ url('information') }}/create/ajax-state?state_id=' + state_id, function(data) {

            console.log(data);

            $('#city').empty();

            $.each(data, function(index,subCatObj){

                $('#city').append('<option value="'+subCatObj.id+'">'+subCatObj.name+'</option>');

            });

        });

    });

</script>

We trigger the script in the State input select on change method. Afterwards we create a route together with the variable the State will pass. The route that we created earlier will capture the URI and return a Json data object, which then again will be captured by our JavaScript. Once the JavaScript has the data object, it will repopulate the City select base on the object our route returns.

That's it you now have a dynamic input select.

Labels: ,