Country State Dynamic Dependent Select Box Using Ajax in Laravel

In this post i will show how to create a very simple dependent select box, Using Ajax in Laravel Framework.

First Step : Create country, State Tables in your Database

Open your Terminal, change Directory to your Project Folder using following Command cd /var/www/Project Folder.

then, run following line of code

php artisan make:migration create_country_state_tables

Once command was Executed, you will get a file in following path database/migrations and put following line of code in your migration file(2017_11_03_042034_create_country_state_tables.php) to create tables into your database.

<?php

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

class CreateCountryStateTables extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('country', function(Blueprint $table){
$table->increments('id');
$table->string('countryname');
$table->timestamps();
});

Schema::create('state', function(Blueprint $table){

$table->increments('id');
$table->integer('country_id');
$table->string('statename');
$table->timestamps();
});
}

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

Now save this file and run migration using following artisan command :

php artisan migrate

Open phpmyadmin then select your Project Database and Execute following Commands on your Selected Databse Sql Command Box

INSERT INTO `country` (`id`, `countryname`, `created_at`, `updated_at`) VALUES
(1, 'India', '2017-11-02 02:18:05', '2017-11-16 04:18:10'),
(2, 'USA', '2017-11-05 04:41:25', '2017-11-12 12:30:14');

INSERT INTO `state` (`id`, `country_id`, `statename`, `created_at`, `updated_at`) VALUES
(1, 1, 'Tamilnadu', '2017-11-10 07:16:44', '2017-11-19 12:18:28'),
(2, 1, 'Kerala', '2017-11-14 07:14:27', '2017-11-07 06:40:12'),
(3, 2, 'Texas', '2017-11-08 11:35:34', '2017-11-20 06:15:26'),
(4, 2, 'Carlifonia', '2017-11-07 08:14:35', '2017-11-07 06:26:26');

Add Following Code in your Route

Route::get('/countrystate', '[email protected]');
Route::get('getstatelist', '[email protected]');

Create CountrystateController.php in your app/Http/Controllers Directory and paste following Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

class CountrystateController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/

public function index()

{
$countries = DB::table('country')->OrderBy('countryname','ASC')->get();

return view('home',compact('countries'));
}

public function getStates(Request $request) {

$states = DB::table("state")->where("country_id",$request->countryid)->OrderBy('statename','ASC')->pluck("statename","id");

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

}

}

Create home.blade.php in /resources/views Directory and paste Following Code

<html>
<head>
<title>Dependent select Dropdown box in Laravel</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-success">
<div class="panel-heading"><h2>Dependent country state Select Box</h2></div>

<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="">

<div class="form-group-sm">

<div class="col-md-6">
<select name="country" id="country" class="form-control">
<option value="">--Select Country--</option>
@foreach ($countries as $countryData)
<option value="{{$countryData->id}}"> {{$countryData->countryname}}</option>
@endforeach
</select>
</div>
<div class="col-md-4">
<select name="state" id="state" class="form-control">
<option>--State--</option>

</select>

</div>

</div>
</form>
</div>

<div class="panel-footer" style="height:50px;">
{{csrf_field()}}
<button class="btn btn-success pull-right" >Submit</button>
</div>
</div>
</div>
</div>
</div>

<script>
$(document).ready(function() {

$('#country').change(function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:"GET",
url:"{{url('getstatelist')}}?countryid="+countryID,
success:function(res){
if(res){
$("#state").empty();
$("#state").append('<option>Select</option>');
$.each(res,function(key,value){
$("#state").append('<option value="'+key+'">'+value+'</option>');
});

}else{
$("#state").empty();
}
}
});
}else{
$("#state").empty();
}
});

});
</script>

</body>
</html>

Now Access your Project /countrystate Route and get Expected Result.

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *