我正在尝试创建动态的两个动态下拉菜单。这些是我的数据库中的服务和类别选择。我需要创建第二个下拉菜单,该菜单是依赖于服务的类别。当我选择[service_code]时,它将根据所选服务提供不同的类别。
这是两个模型之间的关系。
Service.php
public function categories()
{
return $this->hasMany('App\Models\Categories', 'service_id', 'id');
}
Categories.php
public function service()
{
return $this->belongsTo('App\Models\Service', 'service_id');
}
这是我控制器中的代码
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'));
}
以下是我视图中的代码
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>
这是我的请求的脚本部分
<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>
这是定义的路线
Route::get('service/{service}/categories', 'ServiceController@getCategories');
最后这里是控制器中的功能
ServiceController.php
public function getCategories(Service $service)
{
return $service->categories->select('id', 'name')->get();
}
当我在浏览器中打开控制台时出现此错误。
获取http://127.0.0.1:8000/service/3/categories/ 404(未找到)
我尝试按照link中的答案进行操作,但仍然无效......
感谢有人可以提供帮助。
提前致谢。
答案 0 :(得分:1)
route参数是ID,而不是对象。您必须自己获取模型实例。
所以getCategories()
应如下所示:
public function getCategories($idService)
{
$service = Service::findOrFail($idService);
return $service->categories->get(['id','name']);;
}
编辑:如果网址中的ID不是数字(例如:http://127.0.0.1:8000/service/someText/categories/
),为避免收到错误500,请在方法的开头添加一个简单的检查:
if(!is_numeric($idService)) abort(404);