Friday, November 15, 2024
Google search engine
HomeLanguagesLaravel 10 AJAX Dependent Country State City Dropdown Tutorial

Laravel 10 AJAX Dependent Country State City Dropdown Tutorial

If you want to create a dependent County State City dropdown in the Laravel App using Ajax. So you can do it by this tutorial. In this tutorial, you will learn how to create dependent country state city dropdown using Ajax in Laravel 10 applications.

Laravel 10 AJAX Dependent Country State City Dropdown Tutorial

To create a dependent country, state, and city dropdown in Laravel 10, you can follow these steps:

  • Step 1 – Create New Laravel 10 Project
  • Step 2 – Setup Database with Laravel Project
  • Step 3 – Create Migration and Model File
  • Step 4 – Define Routes
  • Step 5 – Create a Controller
  • Step 6 – Create Blade View File
  • Step 7 – Start Development Server
  • Step 8 – Test This App

Step 1 – Create New Laravel 10 Project

In this step, open a terminal or command prompt.

Then execute the following command into it to install or download Laravel 10 app to create dependent country state city dropdown list in Laravel with ajax:

composer create-project --prefer-dist laravel/laravel blog

Step 2 – Setup Database with Laravel Project

In this step, Visit to Laravel 10 app root directory and open the “.env” file.

Then add database details into the .evn file, as follow:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

Step 3 – Create Migration and Model File

In this step, create a migration and model file for the country state city in laravel app.

So execute the following commands on the command prompt or terminal for that:

cd blog

php artisan make:model Country
php artisan make:model State
php artisan make:model City

php artisan make:migration create_country_state_city_tables

Next, Navigate to database/migrations directory and open create_country_state_city_tables.php. Then update the following code into create_country_state_city_tables.php file, as follow:

<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCountryStateCityTables extends Migration
{
    public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
        Schema::create('states', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('country_id');            
            $table->timestamps();
        });
        Schema::create('cities', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('state_id');            
            $table->timestamps();
        });
    }
   public function down()
    {
       Schema::drop('countries');
       Schema::drop('states');
       Schema::drop('cities');
    }
}

Then, run the following command on command prompt:

php artisan migrate

This command will create countries, states, cities tables in your database.

Step 4 – Define Routes

In this step, visit to the routes directory and open web.php file. Then define the following routes into web.php file, as follow:

use App\Http\Controllers\CountryStateCityController;


Route::get('country-state-city', [CountryStateCityController::class, 'index']);
Route::post('get-states-by-country', [CountryStateCityController::class, 'getState']);
Route::post('get-cities-by-state', [CountryStateCityController::class, 'getCity']);

Step 5 – Create a Controller

In this step, create one controller file named CountryStateCityController.php. So open your command prompt or terminal.

Then execute the following command into it to create CountryStateCityControllerfile, as follow:

php artisan make:controller CountryStateCityController

Once you have executed the above command. Now, you need to visit app/http/controllers directory and open CountryStateCityController.php file. Then update the following code into your CountryStateCityController.php file, as follow:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator,Redirect,Response;
use App\Models\{Country,State,City};

class CountryStateCityController extends Controller
{

    public function index()
    {
        $data['countries'] = Country::get(["name","id"]);
        return view('country-state-city',$data);
    }
    public function getState(Request $request)
    {
        $data['states'] = State::where("country_id",$request->country_id)
                    ->get(["name","id"]);
        return response()->json($data);
    }
    public function getCity(Request $request)
    {
        $data['cities'] = City::where("state_id",$request->state_id)
                    ->get(["name","id"]);
        return response()->json($data);
    }

}

Step 6 – Create Blade View File

In this step, Visit resources/views directory And create 1 blade views named country-state-city.blade.php the file inside the directory.

Then open the country-state-city.blade.php file and add the following code into create.blade.php file, as follow:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="csrf-token" content="content">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>Laravel PHP Ajax Country State City Dropdown List - Tutsmake.COM</title>


        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    </head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h2 class="text-success">Laravel Country State City Dependent Dropdown List with Ajax - Tutsmake.COM</h2>
                    </div>
                    <div class="card-body">
                     <form>
                        <div class="form-group">
                          <label for="country">Country</label>
                          <select class="form-control" id="country-dropdown">
                          <option value="">Select Country</option>

                            @foreach ($countries as $country) 
                                <option value="{{$country->id}}">
                                 {{$country->name}}
                                </option>
                            @endforeach
                            
                          </select>
                        </div>
                        <div class="form-group">
                          <label for="state">State</label>
                          <select class="form-control" id="state-dropdown">
                            
                          </select>
                        </div>                        

                        <div class="form-group">
                          <label for="city">City</label>
                          <select class="form-control" id="city-dropdown">
                            
                          </select>
                        </div>
                    </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
<script>

$(document).ready(function() {

    $('#country-dropdown').on('change', function() {
            var country_id = this.value;
             $("#state-dropdown").html('');
            $.ajax({
                url:"{{url('get-states-by-country')}}",
                type: "POST",
                data: {
                    country_id: country_id,
                     _token: '{{csrf_token()}}' 
                },
                dataType : 'json',
                success: function(result){
                    $('#state-dropdown').html('<option value="">Select State</option>'); 
                    $.each(result.states,function(key,value){
                    $("#state-dropdown").append('<option value="'+value.id+'">'+value.name+'</option>');
                    });
                    $('#city-dropdown').html('<option value="">Select State First</option>'); 
                }
            });
        
        
    });    

    $('#state-dropdown').on('change', function() {
            var state_id = this.value;
             $("#city-dropdown").html('');
            $.ajax({
                url:"{{url('get-cities-by-state')}}",
                type: "POST",
                data: {
                    state_id: state_id,
                     _token: '{{csrf_token()}}' 
                },
                dataType : 'json',
                success: function(result){
                    $('#city-dropdown').html('<option value="">Select City</option>'); 
                    $.each(result.cities,function(key,value){
                    $("#city-dropdown").append('<option value="'+value.id+'">'+value.name+'</option>');
                    });

                }
            });
        
        
    });
});
</script>
</body>
</html>

Don’t forget to add country state city script code into your country-state-city.blade.php file, after the closing of body tag:

<script>

$(document).ready(function() {

    $('#country-dropdown').on('change', function() {
            var country_id = this.value;
             $("#state-dropdown").html('');
            $.ajax({
                url:"{{url('get-states-by-country')}}",
                type: "POST",
                data: {
                    country_id: country_id,
                     _token: '{{csrf_token()}}' 
                },
                dataType : 'json',
                success: function(result){
                    $.each(result.states,function(key,value){
                    $("#state-dropdown").append('<option value="'+value.id+'">'+value.name+'</option>');
                    });
                    $('#city-dropdown').html('<option value="">Select State First</option>'); 
                }
            });
        
        
    });    

    $('#state-dropdown').on('change', function() {
            var state_id = this.value;
             $("#city-dropdown").html('');
            $.ajax({
                url:"{{url('get-cities-by-state')}}",
                type: "POST",
                data: {
                    state_id: state_id,
                     _token: '{{csrf_token()}}' 
                },
                dataType : 'json',
                success: function(result){
                    $.each(result.cities,function(key,value){
                    $("#city-dropdown").append('<option value="'+value.id+'">'+value.name+'</option>');
                    });

                }
            });
        
        
    });
});
</script>

Step 7 – Start Development Server

Once you have finished all the above-given steps. Now you need to execute the php artisan command on the terminal or cmd to start the development server:

php artisan serve

Step 8 – Test This App

Now, open your browser and hit the following URL on it:

http://localhost:8000/country-state-city

Conclusion

Laravel 10 dependent country state city dropdown. Here, you have learned how to create dependent dynamic country state city dropdown list in laravel with ajax and live demo.

Recommended Laravel Posts

RELATED ARTICLES

Most Popular

Recent Comments