我想你应该做如下的事情:
public function autoComplete(Request $request){
$query = $request->term;
$res = City::where('name', 'LIKE', "%$query%")->orderBy('name')->paginate(5);
foreach($res as $cities ){
$usersArray[] = array(
"label" => $cities->name,
"value" => $cities->id
);
}
return response()->json($usersArray);
}
查看以下页面:
http://api.jqueryui.com/autocomplete/#option-source
数组:
一
array
可用于本地数据。支持两种格式:
-
字符串数组:
[ "Choice1", "Choice2" ]
-
具有标签和值属性的对象数组:
[ { label: "Choice1", value: "value1" }, ... ]
Array [
Object {
"label": "City",
"value": id
}
];
希望有帮助。
更新
当用户进行选择时,它使用
select
回拨。在上面的示例中
label
value
归因于
价值
所选项目的名称。这可以在这里看到:
http://jqueryui.com/autocomplete/#custom-data
使用自动完成代码,这可能看起来像:
HTML
<div class="search-homepage-input">
{!! Form::open(['route' => 'search.index', 'method' => 'GET']) !!}
<div class="col-md-9">
{!! Form::text('city-name', null, array('class' => 'form-control', 'maxlength' =>'55', 'placeholder' => 'Eg. England, London, Manchester', 'id' => 'sl-label')) !!}
{!! Form::text('city-id', null, array('class' => 'form-control', 'id' => 'sl-id', 'style' => 'display: none;') !!}
</div>
<div class="col-md-3">
{!! Form::submit('Find Teams', array('class' => 'btn btn-homepage')) !!}
</div>
{!! Form::close() !!}
</div>
JavaScript
$('#sl').autocomplete({
source: "/autocomplete",
focus: function(event, ui) {
$("#sl-label").val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#sl-label").val(ui.item.label);
$("#sl-id").val(ui.item.value);
return false;
}
});
通过这种方式,您可以收集要用于搜索的ID。