php Laravel 动态下拉国家和州

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45060108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:04:37  来源:igfitidea点击:

Laravel dynamic dropdown country and state

phpmysqldatabaselaraveldropdown

提问by Kevin

I'm trying to make two dropdown menus. These are the countries and states selections from my database. My problem is don't know how to make conditions that states must be dependent on countries. When I select [countryname] it will give a different selection of states name in my dropdown. So far here what I have done so far.

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

AdminController.php

管理控制器.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

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>

In my database

在我的数据库中

Table:countries

表:国家

+-----------+--------------+------+-----+---------+----------------+
| 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    |                |
+-----------+--------------+------+-----+---------+----------------+

Table:states

表:状态

+------------+------------------+------+-----+---------+----------------+
| 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    |                |
+------------+------------------+------+-----+---------+----------------+

回答by tompec

Here's how to do a dynamic dropdown in Laravel:

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

You can see a demo of how it works here https://www.dronejobs.co/

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

Disclaimer: I didn't test this but it should work. Feel free to comment and I'll update

免责声明:我没有测试过这个,但它应该可以工作。随意评论,我会更新

app/Http/Controllers/HomeController.php

应用程序/Http/Controllers/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(),
        ]);
    }
}

resources/views/home.blade.php

资源/视图/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>

app/Country.php

应用程序/国家/地区.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

app/State.php

应用程序/状态.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

routes/web.php

路线/ web.php

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

app/Http/Controllers/CountryController.php

应用程序/Http/Controllers/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();
    }
}

回答by Kevin

I would like to update this post, I have already solved my problem. I just want to share this solutions for the community :)

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

I just added some ajax codes for this in my user_register.blade.php:

我刚刚在我的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>

Which I specified where to get the data based on country ID and will pass to my routes.php:

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

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

In my routes.php:

在我的routes.php 中

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

Last I added some codes in my AdminController.phpwhat to do:

最后我在我的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;
}

This method works for me. I was able now to dynamically update dropdown option (states) based on Country ID.

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