【问题标题】:Laravel where clause not returning expected resultLaravel where 子句未返回预期结果
【发布时间】:2021-07-03 20:25:26
【问题描述】:

向我的 Laravel 数据库发出请求时出现问题。我正在尝试根据用户输入获取不同的食谱,但 Postman 正在返回“未找到食谱”。 我的 Laravel 控制器代码:

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');
    }
}

如果我返回响应,它会返回 "search": "maken" 和请求 http://127.0.0.1:8000/api/search?search=maken。 然而,当我将 where 子句硬编码为 $recipes = Recipe::where('title', 'LIKE', 'maken')->get(); 时,它会返回一些食谱并且搜索功能有效。现在我不确定错误是在我的 Postman 请求中还是在 Laravel 中的搜索功能中。任何帮助将不胜感激!

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您必须使用$request->INPUT_NAME$request->input('name') 来获取值,所以您的代码应该是:

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

    【讨论】:

      【解决方案2】:

      试试这个方法

      $recipes = Recipe::where('title', 'like', '%' . request('search') . '%')->get();
      
      if ($recipes->count() > 0 ) {
          return response($recipes);
      } else {
          return response('No recipes found');
      }
      

      【讨论】:

        猜你喜欢
        • 2019-07-25
        • 1970-01-01
        • 2021-09-29
        • 1970-01-01
        • 1970-01-01
        • 2021-03-21
        • 2011-08-31
        • 2011-08-09
        • 2010-09-22
        相关资源
        最近更新 更多