首页 > 解决方案 > 未找到 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>

标签: phplaravel

解决方案


发生这种情况是因为您使用的包返回 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


推荐阅读