G Buis
G Buis

Reputation: 303

Laravel where clause not returning expected result

While making a request to my Laravel database something goes wrong. I'm trying to get different recipes on user input but Postman is returning 'No recipes found'. My Laravel controller code:

public function search(Request $request) {
    $fields = $request->validate([
        'search' => 'required|string'
    ]);

    // return response($request);

    $recipes = Recipe::where('title', 'LIKE', '%'.$request.'%')->get();

    if (count($recipes) > 0 ) {
        return response($recipes);
    } else {
        return response('No recipes found');
    }
}

if I return the response it returns "search": "maken" with the request http://127.0.0.1:8000/api/search?search=maken. When I however hardcode the where clause to $recipes = Recipe::where('title', 'LIKE', 'maken')->get(); it returns some recipes and the search function works. Now I'm not sure whether the error is in my Postman request or in my search function in Laravel. Any help would be greatly appreciated!

Upvotes: 0

Views: 219

Answers (2)

Sarwar Ahmed
Sarwar Ahmed

Reputation: 994

Try this way

$recipes = Recipe::where('title', 'like', '%' . request('search') . '%')->get();

if ($recipes->count() > 0 ) {
    return response($recipes);
} else {
    return response('No recipes found');
}

Upvotes: 1

matiaslauriti
matiaslauriti

Reputation: 8081

You have to use $request->INPUT_NAME or $request->input('name') to get the value, so your code should be:

$recipes = Recipe::where('title', 'LIKE', '%'.$request->search.'%')->get();

Upvotes: 2

Related Questions