在Laravel中编辑和填充从属下拉菜单

时间:2019-12-04 23:25:21

标签: php mysql laravel laravel-5 drop-down-menu

我为Laravel创建了一个依赖的下拉菜单,该菜单将连接create.blade.php且完美无缺的国家和州

使用的JavaScript:

jQuery(document).ready(function ()
{
        jQuery('select[name="country"]').on('change',function(){
           var countryID = jQuery(this).val();
           if(countryID)
           {
              jQuery.ajax({
                 type : "GET",
                 url : '<?php echo url('/'); ?>/admin/country/' + (countryID) + '/states/',
                dataType : "json",
                 success:function(data)
                 {
                    console.log(data);
                    jQuery('select[name="state"]').empty();
                    $('select[name="state"]').append('<option value="">{{ trans('global.address.placeholder.state') }}</option>');
                    jQuery.each(data, function(key,value){
                       $('select[name="state"]').append('<option value="'+ key +'">'+ value +'</option>');
                    });
                 }
              });
           }
           else
           {
              $('select[name="state"]').empty();
           }
        });
});

在控制器中

public function getCountries()
{
    $countries = DB::table('countries')->pluck("name","id");
    return json_encode($countries);
}

public function getStates($id) 
{        
    $states = DB::table("states")->where("countries_id",$id)->pluck("name","id");
    return json_encode($states);
}

public function getDistricts($id) 
{        
    $states = DB::table("districts")->where("states_id",$id)->pluck("name","id");
    return json_encode($states);
}

public function getTowns($id) 
{        
    $towns = DB::table("towns")->where("districts_id",$id)->pluck("name","id");
    return json_encode($towns);
}

edit.blade.php中,我正在使用:

                @foreach ($states as $state)
                    <option value="{{ $state->id }}" {{$address->state == $state->id  ? 'selected' : ''}}>{{ $state->name}}</option>
                @endforeach

从数据库中检索选定的数据。到目前为止,一切都很完美,但是在“编辑”部分中,它填充了表状态中数据库中的所有内容,从而跳过了国家/地区ID的依赖性。例如,仅在创建时选择了美国,才显示了世界的所有州而不是美国。我陷入困境,找不到任何人可以帮助的解决方案?

我一直在想的另一件事是,将MySQL数据库中依赖下拉列表的连接更改为连接到资源文件,例如resources> lang> en> country.php和States.php,旨在优化负载。数据库查询以获得更好的性能。有什么建议吗?

0 个答案:

没有答案