Laravel 9 Country State City Dropdown Example

10-Apr-2023

.

Admin

Laravel 9 Country State City Dropdown Example

Hi Dev,

In this post, we will learn how to country state city dynamic dependent dropdown using Ajax and laravel 9. Here you will learn how to country state city using ajax and MySQL laravel 9 dropdown example. This tutorial will give you simple example of dynamic country state dropdown in laravel 9 and Ajax. you'll learn Ajax dynamic dropdown for country. Let's get started with state and city list in laravel 9.

So, let's start the below example

Step 1: Download Laravel


Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app

Step 2: Database Configuration

Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.

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 Country State City Migration and Model File

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;

return new class 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');

}

};

Now, run the migration to create database table using following artisan command:

php artisan migrate

Step 4: Add Route

Here we are ready to we need to define routes in “routes/web.php” file.

routes/web.php

<?php

use App\Http\Controllers\CountryStateCityController;

/*

|--------------------------------------------------------------------------

| 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('country-state-city','CountryStateCityController@index');

Route::post('get-states-by-country','CountryStateCityController@getState');

Route::post('get-cities-by-state','CountryStateCityController@getCity');

Step 5: Add Controller

Next,We are add function in CountryStateCityController.php file so add this way :

app/Http/Controllers/CountryStateCityController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Validator,Redirect,Response;

use App\Models\Country;

use App\Models\State;

use App\Models\City;

class CountryStateCityController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$data['countries'] = Country::get(["name","id"]);

return view('index',$data);

}

/**

* Write code on Method

*

* @return response()

*/

public function getState(Request $request)

{

$data['states'] = State::where("country_id",$request->country_id)

->get(["name","id"]);

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

}

/**

* Write code on Method

*

* @return response()

*/

public function getCity(Request $request)

{

$data['cities'] = City::where("state_id",$request->state_id)

->get(["name","id"]);

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

}

}

At last, create template file for so let's create the index.blade.php file in the emials folder.

Step 6: Add Blade File

resources/views/index.blade.php

<!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</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</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>

Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:

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

It will help you...

#Laravel 9