【问题标题】:Search is not working although item exists in DB尽管数据库中存在项目,但搜索不起作用
【发布时间】:2020-01-24 13:33:04
【问题描述】:

我正在使用 laravel 6:需要用户通过搜索栏查找记录,但它显示 No Available Records

enter image description here 这在我的模型中:类别模型:

public function scopeWhenSearch($query, $search)
{
    return $query->when($search, function ($q) use($search){
            return $q->where('name','like','%$search%');
    });

}   //end of scopeWhenSearch

然后在我的控制器中我在索引时使用了搜索功能:categoryController

public function index()
{
    //

    $categories= Category::whenSearch(request()->search)->paginate(2);
    return view('dashboard.categories.index', compact('categories'));
}

【问题讨论】:

    标签: php search scope controller laravel-6


    【解决方案1】:

    '%$search%' 实际上是在搜索字符串 $search,而不是 $search 包含的任何内容... 在 PHP 中使用 '(单引号)不会从变量中提取值,您需要连接值或使用"(双引号):

    return $query->when($search, function ($q) use($search){
       return $q->where('name', 'LIKE', '%'.$search.'%');
       // or use "
       // return $q->where('name', 'LIKE', "%$search%");
    });
    

    【讨论】:

    • 感谢它的工作
    • 不客气!请使用upvote/accept answer功能表达您的感谢并正确关闭您的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2013-05-25
    • 2016-07-25
    • 1970-01-01
    相关资源
    最近更新 更多