php - 未找到 laravel 模型中的搜索问题
问题描述
我使用了来自 GitHub 的搜索代码,它在本地主机上运行良好。但是当我上传到共享主机上时出现了这个错误
为 foreach() 提供的参数无效(查看:/home/halahit/untitled3/resources/views/terminal/search.blade.php)
当我以 json 形式返回数据时
{
"status": "false",
"message": "this model not found"
}
这是在 laravel 的 web 文件中写的代码
Route::post('search',function (\Illuminate\Http\Request $request){
$terminals=Search::search(
//model
"terminal" ,
//fields you wants to search
['customer' , 'mac_address'] ,
$request->search ,
//back with all raws
null,
['id' , 'asc'] ,
true ,
30
);
return view('terminal.search',compact('terminals'));
});
这是视图
@foreach($terminals as $trm)
<tr>
<td>{{$trm->id}}</td>
<td>{{$trm->customer}}</td>
<th>{{$trm->mac_address}}</th>
<th>{{$trm->modem_type}}</th>
<th>{{$trm->satellite}}</th>
</tr>
@endforeach
这是搜索表格
<form class="form-header" action="/searchh" method="post">
{{csrf_field()}}
<input class="au-input au-input--xl" type="text" name="search" placeholder="Search for customer's info..." />
<button class="au-btn--submit" type="submit">
<i class="zmdi zmdi-search"></i>
</button>
</form>
解决方案
发生这种情况是因为您使用的包返回 JSON,而不是数组或对象,因此您不能foreach
直接返回 JSON。
阅读Search 类的源代码,发现这一行:
return json_encode(['status' => 'false' , 'message' => "this model not found"]);
这意味着搜索方法将在失败的情况下返回一个包含 JSON 的字符串。
要在 PHP 中捕捉这种情况,您需要json_decode
检查字符串并检查是否status
为假:
Route::post('search',function (\Illuminate\Http\Request $request){
$terminals = Search::search(
//model
"terminal" ,
//fields you wants to search
['customer' , 'mac_address'] ,
$request->search ,
//back with all raws
null,
['id' , 'asc'] ,
true ,
30
);
$error = null;
if (is_string($terminals) {
$error = json_decode($terminals);
$terminals = null;
}
return view('terminal.search',compact('error', 'terminals'));
});
那么在你看来:
@if ($terminals)
@foreach($terminals as $trm)
<tr>
<td>{{$trm->id}}</td>
<td>{{$trm->customer}}</td>
<th>{{$trm->mac_address}}</th>
<th>{{$trm->modem_type}}</th>
<th>{{$trm->satellite}}</th>
</tr>
@endforeach
@else
There is an error: {{ $error['message'] }}
@endif
我的推荐
阅读这个包源代码,它看起来很糟糕而且很业余,充满了错误和糟糕的设计。
有一个很好的全文搜索包,我喜欢并使用它,它是 nicolaslopezj/searchable。
另一个不错的软件包是jarektkaczyk/eloquence。
推荐阅读
- c++ - 如何在没有朋友c ++的情况下进行模板分配
- html - 无法从 Excel 单元格复制 URL 并将其发送到网页
- css - SVG 背景图像仅在 Chrome 上不清晰(在 Firefox 和 Safari 上显示正确)
- javascript - 使用 loadModules ReactJS 访问 esri 事件中的状态
- css - TSX 组件中样式标记中 CSS 的语法突出显示
- php - PHP - 仅在 txt 文件中找到匹配项时追加
- typescript - 反应导航抽屉加倍URI参数
- c - 我的 Makefile 中没有发生链接;返回'未定义的对'main'的引用
- dataweave - Dataweave 2.0 with MaxSize 功能
- python - Pandas 中的数据框拆分问题,有什么想法吗?