简体   繁体   English

Laravel基于hasMany关系的动态下拉列表

[英]Laravel dynamic dropdown base on hasMany relationships

I'm trying to create a dynamic two dynamic dropdown menus. 我正在尝试创建一个动态的两个动态下拉菜单。 These are the service and category selection from my database. 这些是从我的数据库中选择的服务和类别。 I need to make the second dropdown menu which is the category that is dependent on the service. 我需要制作第二个下拉菜单,该菜单是取决于服务的类别。 When I select [service_code] it will give a different bunch of categories base on the selected service. 当我选择[service_code]时,它将基于所选服务给出不同的类别。

Here is the relationship between the two models. 这是两个模型之间的关系。

Service.php Service.php

public function categories()
        {
            return $this->hasMany('App\Models\Categories', 'service_id', 'id');
        }

Categories.php Categories.php

public function service()
    {
        return $this->belongsTo('App\Models\Service', 'service_id');
    }

Here is the code in my controller 这是我控制器中的代码

AnalysisRequestController.php AnalysisRequestController.php

public function create()
    {
        $client = Client::all()->sortBy('client_name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('client_name', 'id');
        $services = Service::with('categories')->get()->sortBy('code', SORT_NATURAL | SORT_FLAG_CASE)->pluck('description', 'id');
        $categories = Categories::with('service')->get()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('name', 'id');

        return view('encoder-dashboard.analysis-request.create', compact('client', 'services', 'categories'));
    }

Here is the code in my view 这是我认为的代码

fields.blade.php fields.blade.php

<!-- Service Id Field -->
<div class="form-group col-sm-6">
    {!! Form::label('service_id', 'Service:') !!}
     {!! Form::select('service_id', $services, null, ['class' => 'form-control','required'])!!}
</div>

<!-- Categories Id Field -->
<div class="form-group col-sm-6">
    {!! Form::label('category_id', 'Category:') !!}
     {!! Form::select('category_id', $categories, null, ['class' => 'form-control','required'])!!}
</div>

Here is my script section for the request 这是我的请求脚本部分

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

                var url = '{{ url('service') }}' + $(this).val() + '/categories/';

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

                    select.empty();

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

Here is the defined route 这是定义的路线

Route::get('service/{service}/categories', 'ServiceController@getCategories');

And lastly here is the function in the controller 最后是控制器中的功能

ServiceController.php ServiceController.php

public function getCategories(Service $service)
    {
        return $service->categories->select('id', 'name')->get();
    }

when I open the console in my browser I got this error. 当我在浏览器中打开控制台时,出现此错误。

GET http://127.0.0.1:8000/service/3/categories/ 404 (Not Found) GET http://127.0.0.1:8000/service/3/categories/ 404(未找到)

I tried to follow the answer in this link but still not working.. 我试图按照此链接中的答案进行操作,但仍然无法正常工作

Appreciate if someone could help. 感谢有人可以帮忙。

Thanks in advance. 提前致谢。

The route parameter is an ID, not an object. route参数是一个ID,而不是对象。 You have to get your model instance yourself. 您必须自己获取模型实例。

So getCategories() should look like this: 所以getCategories()应该看起来像这样:

public function getCategories($idService)
{
    $service = Service::findOrFail($idService);
    return $service->categories->get(['id','name']);;
}

Edit: To avoid getting an error 500 if the id in the url is not numeric (example: http://127.0.0.1:8000/service/someText/categories/ , add a simple check at the beginning of your method: 编辑:如果网址中的ID不是数字(例如: http://127.0.0.1:8000/service/someText/categories/ : http://127.0.0.1:8000/service/someText/categories/ : http://127.0.0.1:8000/service/someText/categories/ ,为避免出现错误500,请在方法开头添加一个简单的检查:

if(!is_numeric($idService)) abort(404);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM