Home > database >  Simple Laravel where query fails to run
Simple Laravel where query fails to run

Time:01-27

I'm trying to implement a passable search for my web app and decided to follow along with the Laracasts video here.

This is the form where the request is made:

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

The route that handles the request:

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, 
        ]);
    }
});

And finally the Blade file in which the results should be rendered:

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

No matter how many valid search terms (either part or all of the record's slug) I enter in my form, the search term never returns anything, even while I'm still able to successfully return all the slugs with Manufacturer:all().

I replaced get() with a toSql() for debugging and dumped it into dd(), the result of which seems to confirm that the problem lies in the search term:

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

However, not only is the search term functionally identical to what Jeffrey Way uses in the Laracasts video, I can't get it working no matter how many variations of it with different quoting/concatting methods I try.

What's going on here?

CodePudding user response:

You're not using any parameter, so there's no point in using route model binding

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

Also, if request('search') is evaluated to false, your function will not do anything. With that in mind, your route function should probably be

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'));
});
  •  Tags:  
  • Related