Laravel中使用单个数据库表的Ajax动态相关下拉列表

时间:2018-05-13 18:17:46

标签: ajax select laravel-5

我正在使用Laravel,我想填充我的选择框和他的动态依赖。我有一个单独的表“位置”与国家,州,城市。

1 个答案:

答案 0 :(得分: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',

就这样。现在,您将能够实现从数据库中提取数据的动态选择功能。