Laravel动态下拉国家和州

时间:2017-07-12 14:11:46

标签: php mysql database laravel dropdown

我正在尝试制作两个下拉菜单。这些是我的数据库中的国家/地区和州选择。我的问题是不知道如何制定国家必须依赖国家的条件。当我选择[countryname]时,它会在我的下拉列表中给出不同的州名称选择。到目前为止,我到目前为止所做的一切。

AdminController.php

public function user_register()
    {
        $countryname = DB::table('countries')
            ->get();
        $statename = DB::table('states')
            ->get();

        $title = ucwords(Lang::get('constants.user') . ' ' . Lang::get('constants.register')); 
        return View::make('register.user_register')
            ->with('title', $title)
            ->with('page', 'user_register')
            ->with('countryname', $countryname)
            ->with('statename', $statename)
    }

user_register.blade.php

<select class="form-control" id="countries" name="countries">
    <option value="">Please select</option>
        <?php foreach ($countryname as $key=>$countryname): ?>
        <option value="<?php echo $countryname->sortname; ?>"<?php
         if (isset($countries) && Input::old('countries') == $countryname->sortname) 
         {
             echo 'selected="selected"';
         }
         ?>>
         <?php  echo $countryname->sortname ." - ". $countryname->name  ; ?>
    </option>
    <?php endforeach; ?>
</select>


<select class="form-control" id="states" name="states">
    <option value="">Please select</option>
        <?php foreach ($statename as $key=>$statename): ?>
        <option value="<?php echo $countryname->name; ?>" <?php
        if (isset($states) && Input::old('states') == $statename->name)
        {
            echo 'selected="selected"';
        }
        ?>>
        <?php  echo $statename->name; ?></option>
        <?php endforeach; ?>
</select>

在我的数据库中

表: 国家/地区

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| country_id| int(11)      | NO   | PRI | NULL    | auto_increment |
| sortname  | varchar(3)   | NO   |     | NULL    |                |
| name      | varchar(150) | NO   |     | NULL    |                |
| phonecode | int(11)      | NO   |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

表:

+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255)     | NO   |     | NULL    |                |
| country_id | int(11)          | NO   |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+

2 个答案:

答案 0 :(得分:8)

以下是如何在Laravel中进行动态下拉列表:

  

您可以在此处查看有关其工作原理的演示https://www.dronejobs.co/

免责声明:我没有对此进行测试,但它应该可行。随意评论,我会更新

应用程序/ HTTP /控制器/ HomeController.php

<?php

namespace App\Http\Controllers;

use App\{Country, State};

class HomeController extends Controller
{
    public function index()
    {
        return view('home', [
            'countries' => Country::all(),
            'states' => State::all(),
        ]);
    }
}

资源/视图/ home.blade.php

<select name="country">
    @foreach ($countries as $country)
        <option value="{{ $country->id }}">{{ $country->name }}</option>
    @endforeach
</select>

<select name=“state”>
    @foreach ($states as $state)
        <option value="{{ $state->id }}">{{ $state->name }}</option>
    @endforeach
</select>

<script>
    $(function() {
        $('select[name=country]').change(function() {

            var url = '{{ url('country') }}' + $(this).val() + '/states/';

            $.get(url, function(data) {
                var select = $('form select[name= state]');

                select.empty();

                $.each(data,function(key, value) {
                    select.append('<option value=' + value.id + '>' + value.name + '</option>');
                });
            });
        });
    });
</script>

应用程序/ Country.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{   
    public function states()
    {
        return $this->hasMany('App\State');
    }

应用程序/ State.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

Class State extends Model
{   
    public function country()
    {
        return $this->belongsTo('App\Country');
    }

路由/ web.php

Route::get('country/{country}/states', 'CountryController@getStates');

应用程序/ HTTP /控制器/ CountryController.php

<?php

namespace App\Http\Controllers;

use App\Country;

class CountryController extends Controller
{
    public function getStates(Country $country)
    {
        return $country->states()->select('id', 'name')->get();
    }
}

答案 1 :(得分:2)

我想更新这篇文章,我已经解决了我的问题。我只是想为社区分享这个解决方案:)

我刚刚在 user_register.blade.php 中添加了一些ajax代码:

    <div class="form-group">
        <label for="title">Select Country:</label>
        <select name="country" class="form-control">
            <option value="">--- Select country ---</option>
            @foreach ($countries as $key => $value)
                <option value="{{ $value }}">{{ $value }}</option>
            @endforeach
        </select>
    </div>
    <div class="form-group">
        <label for="title">Select state:</label>
        <select name="state" class="form-control">
        </select>
    </div>
    <script type="text/javascript">
    $(document).ready(function() {
    $('select[name="country"]').on('change', function() {
        var countryID = $(this).val();
            if(countryID) {
            $.ajax({
                url: '/admin/user_register/ajax/'+encodeURI(countryID),
                type: "GET",
                dataType: "json",
                success:function(data) {
                $('select[name="state"]').empty();
                $.each(data, function(key, value) {
                    $('select[name="state"]').append('<option value="'+ value +'">'+ value +'</option>');
                    });
                }
            });
            }else{
            $('select[name="state"]').empty();
              }
           });
        });
    </script>

我指定了哪里根据国家/地区ID获取数据,并将传递给我的routes.php:

url: '/admin/user_register/ajax/'+encodeURI(countryID),

在我的 routes.php

    //dynamic dropdown country and states
Route::get('/admin/user_register/ajax/{country_id}',array('as'=>'user_register.ajax','uses'=>'AdminController@stateForCountryAjax'));

最后我在 AdminController.php 中添加了一些代码:

public function stateForCountryAjax($country_name)
{
    $country_name = urldecode($country_name);
    $country_id = $this->_stateCountryIDForCountryName($country_name);
    $states = DB::table("states")
                ->where("country_id",$country_id)
                ->lists('name','id');
    return json_encode($states);
}

private function _stateCountryIDForCountryName($country_name)
{
    return DB::table('countries')->where("name","$country_name")->first()->country_id;
}

这种方法适合我。我现在能够根据国家ID动态更新下拉选项(状态)。