Laravel动态下拉国家和州

Kev*_*vin 9 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)
    }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

在我的数据库中

表: 国家

+-----------+--------------+------+-----+---------+----------------+
| 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    |                |
+-----------+--------------+------+-----+---------+----------------+
Run Code Online (Sandbox Code Playgroud)

表: 状态

+------------+------------------+------+-----+---------+----------------+
| 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    |                |
+------------+------------------+------+-----+---------+----------------+
Run Code Online (Sandbox Code Playgroud)

小智 10

以下是如何在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(),
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

资源/视图/ 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>
Run Code Online (Sandbox Code Playgroud)

应用程序/ Country.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

应用程序/ State.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

路线/ web.php

Route::get('country/{country}/states', 'CountryController@getStates');
Run Code Online (Sandbox Code Playgroud)

应用程序/ 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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Kev*_*vin 6

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

我刚刚在我的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>
Run Code Online (Sandbox Code Playgroud)

我根据国家/地区 ID 指定从何处获取数据并将传递给我的 routes.php:

url: '/admin/user_register/ajax/'+encodeURI(countryID),
Run Code Online (Sandbox Code Playgroud)

在我的routes.php 中

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

最后我在我的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;
}
Run Code Online (Sandbox Code Playgroud)

这个方法对我有用。我现在能够根据国家/地区 ID 动态更新下拉选项(状态)。