Laravel Country State City Dropdown Using AJAX

  • 01-09-2022
  • 729
  • Laravel 9
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

Laravel country state city dropdown using ajax is the most important part while you develop the laravel form and ask users for address details through the country, state, and city.

Country State City Dropdown List Using Ajax In Laravel; firstly we will create laravel that three table migration. Then after we will import ready the three table data into the database.

Laravel Dropdown Fetch Data From API; Once the import data we will select the country and based on the country we will show to use that country state, then based on the state we will get city dropdown data based on state id.

For fetching data from the database base on id, we will take the help of ajax, because at that time you can not able to refresh else your pre-data filled may erase. So in that case you must need to use ajax to get other dropdown data based on other that's ids.

To getting Download Country State City .sql file. Goto the end of this post there will be a DOWNLOAD SOURCE button, Just click you will be download zip file.

Step 1. Create Country Migration

Create country migration as well as a model using the below-provided command, open your terminal and paste this command.

Goto, your country created migration and paste the given up and down method in your country migration.

php artisan make:model Country -m

Laravel 9 Ajax Image Upload With Preview Tutorial

database/migrations/2022_08_30_053908_create_countries_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCountriesTable extends Migration
{
    /**
        * Run the migrations.
        *
        * @return void
        */
    public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('sortname');
            $table->string('phonecode');
            $table->timestamps();
        });
    }

    /**
        * Reverse the migrations.
        *
        * @return void
        */
    public function down()
    {
        Schema::dropIfExists('countries');
    }
}

Step 2. Create State Migration

Create state migration as well as a model using the below-provided command, open your terminal, and paste this command.

Open your state migration and add a field like the below given, copy up and down both methods in paste in your state migration.

php artisan make:model State -m
database/migrations/2022_08_30_053952_create_states_table.php
<?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    class CreateStatesTable extends Migration
    {
        /**
            * Run the migrations.
            *
            * @return void
            */
        public function up()
        {
            Schema::create('states', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->integer('country_id');
                $table->timestamps();
            });
        }
    
        /**
            * Reverse the migrations.
            *
            * @return void
            */
        public function down()
        {
            Schema::dropIfExists('states');
        }
    }
    

Step 3. Create City Migration

Create city migration as well as a model using the below-provided command, open your terminal, and paste this command.

Goto your city migration and create a field as given in the below example.

php artisan make:model City -m
database/migrations/2022_08_30_054051_create_cities_table.php
<?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    class CreateCitiesTable extends Migration
    {
        /**
            * Run the migrations.
            *
            * @return void
            */
        public function up()
        {
            Schema::create('cities', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->integer('state_id');
                $table->timestamps();
            });
        }
    
        /**
            * Reverse the migrations.
            *
            * @return void
            */
        public function down()
        {
            Schema::dropIfExists('cities');
        }
    }

Step 4. Routes

Now, create a route using provided below command, This command will create a dropdown controller in the controller root in our application.

php artisan make:controller DropDownController

Import dropdown controller in route file at the top as per the example given.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DropDownController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('dropdown',[DropDownController::class,'index']);
Route::post('api/fetch-state',[DropDownController::class,'fatchState']);
Route::post('api/fetch-cities',[DropDownController::class,'fatchCity']);

Step 4. Dropdown Controller

We will define all that methods in the controller. Follow the below given example just copy and paste it into your app.

app/Http/Controllers/DropDownController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\{Country,City,State}; // IMPORT MODEL

class DropDownController extends Controller
{
    public function index()
    {
        $counteries = Country::get(['name','id']);

        return view('dropdown',compact('counteries'));
    }

    public function fatchState(Request $request)
    {
        $data['states'] = State::where('country_id',$request->country_id)->get(['name','id']);

        return response()->json($data);
    }

    public function fatchCity(Request $request)
    {
        $data['cities'] = City::where('state_id',$request->state_id)->get(['name','id']);

        return response()->json($data);
    }
}

Step 5. View Blade File

Here, View the file for that three dropdowns. by default the country data will come from the request. After that, once you select a country, based on that country id we will fetch state data, and based on the state id we will list the dropdown of the city. So fetching that data we will take the help of ajax that retrieves data without refreshing the page.

resources/views/dropdown.blade.php
<!doctype html>
<html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css">
    <title>Laravel Country State City Dropdown Using AJAX - Webappfix</title>
    </head>
    <body>
    <div class="container mt-4">
        <div class="row justify-content-center">
        <div class="col-md-5">
            <h2>Laravel Country State City Dropdown Using AJAX - Webappfix</h2>
            <form>
            <div class="form-group mb-3">
                <select id="country-dd" class="form-control">
                <option value="">Select Country</option>
                @foreach($counteries as $data)
                    <option value="{{$data->id}}">{{$data->name}}</option>
                @endforeach
                </select>
            </div>
            <div class="form-group mb-3">
                <select id="state-dd" class="form-control"></select>
            </div>
            <div class="form-group mb-3">
                <select id="city-dd" class="form-control"></select>
            </div>
            </form>
        </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>

    // CUSTOM FETCH DROPDOWN AJAX SCRIPT
    <script type="text/javascript">
    
    // FETCH STATE DROPDOWN
        $(document).ready(function() {
        $('#country-dd').change(function(event) {
            var idCountry = this.value;
            $('#state-dd').html('');

            $.ajax({
            url: "/api/fetch-state",
            type: 'POST',
            dataType: 'json',
            data: {country_id: idCountry,_token:"{{ csrf_token() }}"},
            success:function(response){
                $('#state-dd').html('<option value="">Select State</option>');
                $.each(response.states,function(index, val){
                $('#state-dd').append('<option value="'+val.id+'"> '+val.name+' </option>')
                });
                $('#city-dd').html('<option value="">Select City</option>');
            }
            })
        });

        // FETCH CITY DROPDOWN
        $('#state-dd').change(function(event) {
            var idState = this.value;
            $('#city-dd').html('');
            $.ajax({
            url: "/api/fetch-cities",
            type: 'POST',
            dataType: 'json',
            data: {state_id: idState,_token:"{{ csrf_token() }}"},
            success:function(response){
                $('#city-dd').html('<option value="">Select State</option>');
                $.each(response.cities,function(index, val){
                $('#city-dd').append('<option value="'+val.id+'"> '+val.name+' </option>')
                });
            }
            })
        });
        });
    </script>
</body>
</html>

Step 6. Start Development Server

Start Your development server using the below-provided command in your app terminal.

php artisan serve

Open your browser and run the below URL in your browser it will show you a list of country dropdowns along with two other dropdowns. The state and city dropdown will select based on country and state.

http://127.0.0.1:8000/dropdown

Laravel 9 Ajax Login Form Submit With Validation Handled


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :