0

im using Laravel and i want to populate my select box and his dynamic depend. I have a single table "Location" with country, state, city.

3
  • What is your question? Commented May 13, 2018 at 18:27
  • I followed this tutorial, I did exactly the same as it does but it only picks the countries - webslesson.info/2018/03/… Commented May 13, 2018 at 18:55
  • I need to do what he did Commented May 13, 2018 at 18:56

1 Answer 1

1
    Step 1:First of all create three tables country, state and city and insert dummy 
    data. You can generate dummy data from model factory which uses fake data.

    For example:
    This is my table..

    public function up()
        {
            Schema::create('countries', function (Blueprint $table) {
                $table->increments('id');
                $table->string('sortname');
                $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');
        }


    Step 2: Define the routes
    This is mine..
    Route::get('api/dependent-dropdown','APIController@index');
    Route::get('api/get-state-list','APIController@getStateList');
    Route::get('api/get-city-list','APIController@getCityList');

    Step 3: Create a controller as APIController.php as this is in my route after the url.
    <?php
    namespace App\Http\Controllers;
    use App\Http\Requests;
    use Illuminate\Http\Request;
    use DB;
    class APIController extends Controller
    {
        public function index()
        {
            $countries = DB::table("countries")->lists("name","id");
            return view('index',compact('countries'));
        }
        public function getStateList(Request $request)
        {
            $states = DB::table("states")
                        ->where("country_id",$request->country_id)
                        ->lists("name","id");
            return response()->json($states);
        }
        public function getCityList(Request $request)
        {
            $cities = DB::table("cities")
                        ->where("state_id",$request->state_id)
                        ->lists("name","id");
            return response()->json($cities);
        }
    }

    Step 4: Your controller is created, but you need to view it on a page, so create a view file named index.blade.php

    My index.blade file is like this:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Dependent country state city dropdown using ajax in PHP Laravel Framework</title>
        <link rel="stylesheet" href="http://www.expertphp.in/css/bootstrap.css">    
        <script src="http://demo.expertphp.in/js/jquery.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="panel panel-default">
          <div class="panel-heading">Dependent country state city dropdown using ajax in PHP Laravel Framework</div>
          <div class="panel-body">
                <div class="form-group">
                    <label for="title">Select Country:</label>
                    {!! Form::select('country', ['' => 'Select'] +$countries,'',array('class'=>'form-control','id'=>'country','style'=>'width:350px;'));!!}

                </div>
                <div class="form-group">
                    <label for="title">Select State:</label>
                    <select name="state" id="state" class="form-control" style="width:350px">
                    </select>
                </div>

                <div class="form-group">
                    <label for="title">Select City:</label>
                    <select name="city" id="city" class="form-control" style="width:350px">
                    </select>
                </div>
          </div>
        </div>
    </div>
    <script type="text/javascript">
        $('#country').change(function(){
        var countryID = $(this).val();    
        if(countryID){
            $.ajax({
               type:"GET",
               url:"{{url('api/get-state-list')}}?country_id="+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();
            $("#city").empty();
        }      
       });
        $('#state').on('change',function(){
        var stateID = $(this).val();    
        if(stateID){
            $.ajax({
               type:"GET",
               url:"{{url('api/get-city-list')}}?state_id="+stateID,
               success:function(res){               
                if(res){
                    $("#city").empty();
                    $.each(res,function(key,value){
                        $("#city").append('<option value="'+key+'">'+value+'</option>');
                    });

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

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

    Step 5: You might get some errors like HTML of FORM. 
    If you got errors like that you need to add the following code on your composer.json file which is inside laravel directory.
    "require": {

    "laravel/framework": "5.0.*",

    "laravelcollective/html": "~5.0"

    },

    OR

    You can also ask laravel to install these above code of composer.json 
    For that you need to install laravelcollective for html which can be installed by

    composer require laravelcollective/html

    Step 6: After this, composer will load the HTML and FORM class, now you just need to 
    provide the alias name.

    Open app.php file which is located on config folder(config/app.php) and add the 
    following line to service providers.
    'Collective\Html\HtmlServiceProvider',

    Step 7: Next you need to add the path of form and html on aliases arrry.

    Add the following code to aliases array.

    'Form' => 'Collective\Html\FormFacade',

    'HTML' => 'Collective\Html\HtmlFacade',

So, that it. Now, you will be able to implement dynamic select feature which fetches data from database.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.