Load cities from state laravel

4.4k views Asked by At

I am working with laravel, right now, i am making an user registry Form, i am relating the state and its cities, so, i need to change a select field values according the state that user chooses.

I have something in the form:

{{ Form::select('city', $city, array('id', 'city')}}

If i use the {{Form::select}} fields in conventional way it charges all the cities from one state, so, when the user select a state, it must change the list of cities in the select field.

I searched but i didn't find any. How can i do that?

thanks.

3

There are 3 answers

1
Mas Hary On
public function getCities($province_id)
    {
        $cities = Cities::where('province_id', '=', $province_id)->get(['id', 'name']);
        return Response::json(array('error' => 0, 'cities' => $cities));
    }
0
manuelpgs On

You can use ajax with jQuery.

In your view set an event when the state change, like this:

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

        // empty the select with previous cities if we have.
        $('#cities').empty();            

        $.ajax({
                type: "POST",
                dataType: "json",
                // actions is a controller
                // cities is a method of actions controller
                url : "{{ URL::to('actions/cities') }}",
                //here we set the data for the post based in our form 
                data : $('#MyFormID').serialize(),
                success:function(data){                    
                        if(data.error === 0 ){ // all was ok                                

                        for (var i = 0; i < data.cities.length; i++) { 
                            $('#cities').append("<option value='"+data.cities[i].id+"'>"+data.cities[i].city_name+"</option>")
                        }

                        }else{
                            alert(data);
                        }
                },
                timeout:10000
        });                         
    });

actions/cities controller

//remember, this is a post method
public function postCities(){

    // validate            
    $validator = Validator::make(Input::all(), 
        array(
            'state_id' => 'required|integer'
    ));        

    if ($validator->fails()) {
        return Response::json(array('error' => 1, 'message' => 'State is required'));
    }

    //City is your model, I assumes that you pkey is ID and the city name is city_name and your fkey is state_id
    $cities = City::where('state_id', '=', Input::get('state_id'))->get();

    return Response::json(array('error' => 0, 'cities' => $cities));

}
0
igaster On

You might want to check a sample vue component that ships with my package Laravel Cities that performs exactly what you are trying to build.

This is a simple package that allows you seed localy all the cities of any country on the world (provided by geonames.org) and perform any query with the provided Eloquent model. It exposes an HTTP API and a vue component that allows you to select any city through a series of steps.

You can insert it in your forms like any other input field:

<form action="post-url" method="POST">
    <geo-select></geo-select>
    <!-- Add more form fields here... -->
    <input type="submit">
</form>

With the provided Eloquent model You can perform queries like this:

// Get the States of USA in aplhabetic order
Geo::getCountry('US')
  ->children()
  ->orderBy('name')
->get();

Sorry, no demo yet, but you can check some sceenshots on the github page...