COUNTRY NAME WISE STATE NAME FETCH IN jQuery and Laravel.

  • Post author:
  • Post category:Laravel
  • Post comments:0 Comments
  • Post last modified:January 18, 2021
  • Reading time:7 min(s) read

In this tutorial, we are going to study how to fetch country name-wise state title fetch with the assist of jQuery, Laravel, and MySql. In the previous tutorial, we have learned how to insert data, select/retrieve or fetch data, update and delete data from the database using LARAVEL. If you have missed the previous ones it is suggested to go through the LARAVEL series.

Now, it’s time to learn how to fetch country names from the MySQL table and show all country names on the dropdown. Click each country name get the all-state name for that country with help of Bootstrap 4, jQuery, Ajax, Laravel 8, and MySQL.

At first  Download country and state, SQL click here then  Create a database and import the country and state SQL.

Now to create a blade page i.e, welcome.blade.php, and write the HTML codes. To show the country  and state name on the dropdown section, build two dropdown sections. HTML codes are given below.

@extends('master')
@section('content')
<div class="container">
    <div class="row">
        <div class="card">
            <div class="card-header">
                <div class="text-center">
                    <h1>Country Name Wise State Fetch Using Laravel 8</h1>
                </div>
            </div>
            <div class="card-body">
                <form>
                    <div class="row">
                        <div class="col-md-12">
                            <label>USER NAME</label>
                            <input type="text" class="form-control" name="user_name" id="user_name">
                        </div>
                                 {{csrf_field()}}
                        
                        <div class="col-md-12">
                            <label>COUNTRY NAME</label>
                            <select class="form-control" name="country" id="country">
                                <option selected="" disabled="">SELECT COUNTRY</option>
                                <?php

                                    foreach ($country as $key) {
                                ?>
                                <option value="{{$key->id}}">{{$key->name}}</option>
                                <?php
                                }
                                ?>
                            </select>
                        </div>
                        <div class="col-md-12">
                            <label>STATE NAME</label>
                            <select class="form-control" id="state" name="state">
                                <option selected="" disabled="">SELECT STATE</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

@stop
jQuery

Create models for country table and state table, also create a controller and make a function that is

<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use DB;


class Mycontroller extends Controller
{
    public function Dashboard()
    {
    	$fetch_country= DB::table('countries')->get();
    	$capsule = array('country' =>$fetch_country);
    	return view('welcome')->with($capsule);
    }
    
}

here is the models code: for country

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    protected $table = 'countries';
}

Don’t forgot to add routes in web.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Mycontroller;

/*
|--------------------------------------------------------------------------
| 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('/', [Mycontroller::class, 'Dashboard']);
Route::post('/getState', [Mycontroller::class, 'getState']);

Now fetch states name using AJAX and JQuery

To get the country id use the change() method .Here is the jquery script code

$(document).ready(function(){
    $('#country').on('change',function(){
    	var id = $(this).val();
    	var _token = $('input[name="_token"]').val();
    	$.ajax({
	        type:'POST',
            url: 'getState',
            data: {_token:_token,id:id},
            dataType:'json', 
            success:function(data){
                console.log("success");
                console.log(data);
                $('#state').html(data);
            }
	    });
    });
});

now get the data here is the controller code

public function getState(Request $request)
    {
       $id=$request->id;
       //print_r($id);
       $get_states=DB::table('states')->where('country_id',$id)->get();
        //print_r($get_states);
        $output='<option selected="" disabled="">SELECT STATE</option>';
        foreach ($get_states as $key) {
            $output.='<option value="'.$key->id.'">'.$key->name.'</option>';
        }
        echo json_encode($output);
    }

  here is the model code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class State extends Model
{
    use HasFactory;
    protected $table= "states";
}

For Live demo clike here

Here is the video for this tutorial.

now hear is the complete code.

Routes (web.php).

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Mycontroller;

/*
|--------------------------------------------------------------------------
| 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('/', [Mycontroller::class, 'Dashboard']);
Route::post('/getState', [Mycontroller::class, 'getState']);

Controller, (i.e, Mycontroller.php) code here

<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use DB;


class Mycontroller extends Controller
{
    public function Dashboard()
    {
    	$fetch_country= DB::table('countries')->get();
    	$capsule = array('country' =>$fetch_country);
    	return view('welcome')->with($capsule);
    }
    public function getState(Request $request)
    {
       $id=$request->id;
       //print_r($id);
       $get_states=DB::table('states')->where('country_id',$id)->get();
        //print_r($get_states);
        $output='<option selected="" disabled="">SELECT STATE</option>';
        foreach ($get_states as $key) {
            $output.='<option value="'.$key->id.'">'.$key->name.'</option>';
        }
        echo json_encode($output);
    }
}

model code for country and state here

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    protected $table = 'countries';
}

//////STATE /////
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class State extends Model
{
    use HasFactory;
    protected $table= "states";
}

HTML CODE HERE

master.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.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>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="{{url('js/custom.js')}}"></script>
</head>
<body>

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>    
    </ul>
  </div>  
</nav>
<br>

@yield('content')

</body>
</html>

Welcome.blade.php

@extends('master')
@section('content')
<div class="container">
    <div class="row">
        <div class="card">
            <div class="card-header">
                <div class="text-center">
                    <h1>Country Name Wise State Fetch Using Laravel 8</h1>
                </div>
            </div>
            <div class="card-body">
                <form>
                    <div class="row">
                        <div class="col-md-12">
                            <label>USER NAME</label>
                            <input type="text" class="form-control" name="user_name" id="user_name">
                        </div>
                                 {{csrf_field()}}
                        
                        <div class="col-md-12">
                            <label>COUNTRY NAME</label>
                            <select class="form-control" name="country" id="country">
                                <option selected="" disabled="">SELECT COUNTRY</option>
                                <?php

                                    foreach ($country as $key) {
                                ?>
                                <option value="{{$key->id}}">{{$key->name}}</option>
                                <?php
                                }
                                ?>
                            </select>
                        </div>
                        <div class="col-md-12">
                            <label>STATE NAME</label>
                            <select class="form-control" id="state" name="state">
                                <option selected="" disabled="">SELECT STATE</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

@stop
finamecuntryname wise state name

here is the jquery ajax script

$(document).ready(function(){
    $('#country').on('change',function(){
    	var id = $(this).val();
    	var _token = $('input[name="_token"]').val();
    	$.ajax({
	        type:'POST',
            url: 'getState',
            data: {_token:_token,id:id},
            dataType:'json', 
            success:function(data){
                console.log("success");
                console.log(data);
                $('#state').html(data);
            }
	    });
    });
});

Leave a Reply