DEV Community

Chandni Soni
Chandni Soni

Posted on

4

Laravel : Country - State - City Dropdown with AJAX

Many people have struggle with this topic and they can not get the output and some also complains that they get empty dropdown, so here I am writing my second post on medium and sharing my self tried code snippet with html-javascript file, controller file and route file. So let's begin...

First we need a blade.php file:

        <select class="form-control" name="country" id="country">
            <option value="">Select Country</option>
            @foreach ($countries as $country) 
                <option value="$country->country_id">
                 $country->country_name
                </option>
            @endforeach
        </select>

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

        <select class="form-control" name="city" id="city">
        </select>

Then we need a JavaScript file:

        $('#country').change(function(){
        var cid = $(this).val();
        if(cid){
        $.ajax({
           type:"get",
           url:" url('/state') /"+cid, **//Please see the note at the end of the post**
           success:function(res)
           {       
                if(res)
                {
                    $("#state").empty();
                    $("#city").empty();
                    $("#state").append('<option>Select State</option>');
                    $.each(res,function(key,value){
                        $("#state").append('<option value="'+key+'">'+value+'</option>');
                    });
                }
           }

        });
        }
    });
    $('#state').change(function(){
        var sid = $(this).val();
        if(sid){
        $.ajax({
           type:"get",
           url:"url('/city')/"+sid, **//Please see the note at the end of the post**
           success:function(res)
           {       
                if(res)
                {
                    $("#city").empty();
                    $("#city").append('<option>Select City</option>');
                    $.each(res,function(key,value){
                        $("#city").append('<option value="'+key+'">'+value+'</option>');
                    });
                }
           }

        });
        }
    }); 

After that we need to create a controller which fetch all data we need from the database. So here is a code of Controller file:

//For fetching all countries
public function getCounties()
{
    $countries= DB::table("countries")->get();
    return view('index')->with('countries',$countries);
}

//For fetching states
public function getStates($id)
{
    $states = DB::table("states")
                ->where("country_id",$id)
                ->pluck("state_name","id");
    return response()->json($states);
}

//For fetching cities
public function getCities($id)
{
    $cities= DB::table("cities")
                ->where("state_id",$id)
                ->pluck("city_name","id");
    return response()->json($cities);
}

and now last but not the least the route file, which is use to reach to the functions we have created. So let's see the code of rote file:

Route::get('/getCountries','YourController@getCountries');
Route::get('/getStates/{id}','YourController@geStates');
Route::get('/getCities/{id}','YourController@geCities');

Note: Please put curly brackets around url:"(two start curly braces here)url('/state')(two end curly braces here)/"+cid. Tried it to put on code but it shows me an error that Liquid error: Liquid variables are disabled
If anyone has solution for the same then please comment here so next time when I upload code snippets I can use that.

Happy Codding...
Thank you for reading...

Top comments (4)

Collapse
 
sherifrihan profile image
Sherif Rihan

this is just awesome
u did exactly what i had 3 days searching for

Collapse
 
chandni279 profile image
Chandni Soni

Thank you :)

Collapse
 
esirei profile image
Esirei

Hey! Did you use a library to populate the countries, states and cities tables, I'm working on a project and need a dataset to work with.

Collapse
 
chandni279 profile image
Chandni Soni

no I didn't use any library for that.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️