0

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!

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

Comments

1

Try this way

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.