我使用了来自GitHub的搜索代码,它在本地主机上运行良好。但是当我在共享主机上上传时,出现了此错误
为foreach()提供的参数无效(查看:/home/halahait/untitled3/resources/views/terminal/search.blade.php)
当我将数据作为json返回时
{
"status": "false",
"message": "this model not found"
}
这是在laravel中的网络文件中编写的代码
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>
答案 0 :(得分:0)
之所以会这样,是因为您使用的包返回的是JSON,而不是数组或对象,因此您不能直接foreach
JSON。
阅读source code for 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。