简单 Laravel 查询失败 运行

Simple Laravel where query fails to run

我正在尝试为我的 Web 应用程序实施可通过的搜索,并决定跟随 Laracasts 视频 here

这是提出请求的表格:

<form action="find-manufacturer/" class="search-form" method="GET">
    <input type="text" placeholder="Search for your manufacturer" name="search" id="search" autocomplete="off" value="{{ request("search") }}"> 
</form>

处理请求的路由:

Route::get("find-manufacturer/", function (Manufacturer $manufacturer) {
    if (request("search")) {
        $manufacturers = Manufacturer::where('slug', 'like', '%' . request("search") . '%')->get();

        return view("search-results", [
            "manufacturer" => $manufacturer,  // This variable is irrelevant to the current problem, but doesn't seem to be causing a conflict either                                               
            "manufacturers" => $manufacturers, 
        ]);
    }
});

最后是渲染结果的 Blade 文件:

@if($manufacturers->isNotEmpty())
    @foreach ($manufacturers as $manufacturer)
        {{ $manufacturer->slug }}
    @endforeach
@else
    <div>
        <p><h1>No results found.</h1></p>
    </div>
@endif

无论我在表单中输入多少有效搜索词(记录的部分或全部),搜索词都不会 return 任何东西,即使我仍然能够成功 return 所有带有 Manufacturer:all().

的鼻涕虫

我用toSql()替换了get()进行调试,并转储到dd(),结果似乎证实了问题出在搜索词上:

"select * from `manufacturers` where `slug` like ?"

但是,不仅搜索词在功能上与 Jeffrey Way 在 Laracasts 视频中使用的相同,而且无论我尝试使用不同的 quoting/concatting 方法进行多少变体,我都无法正常工作。

这是怎么回事?

您没有使用任何参数,因此使用路由模型绑定没有意义

Route::get("find-manufacturer/", function (Manufacturer $manufacturer) {...});

此外,如果 request('search') 的计算结果为 false,您的函数将不会执行任何操作。考虑到这一点,您的路线功能可能应该是

Route::get("find-manufacturer/", function () {
    if (request("search")) {
        $manufacturers = Manufacturer::where('slug', 'like', '%' . request("search") . '%')->get();
    } else {
        $manufacturers = collect();
    }

    return view("search-results", compact('manufacturers'));
});