Skip to content
Advertisement

Search is not working although item exists in DB

I am using laravel 6 : need user to find records by search bar, but it shows No Available Records

enter image description here this in my model:Category model:

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

}   //end of scopeWhenSearch

Then in my controller I used in the index when search function:categoryController

public function index()
{
    //

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

Advertisement

Answer

'%$search%' is literally searching for the string $search, not whatever $search contains… Using '(single quotes) in PHP doesn’t extract the value from the variable, you need to concatenate the value or use "(double quotes):

return $query->when($search, function ($q) use($search){
   return $q->where('name', 'LIKE', '%'.$search.'%');
   // or use "
   // return $q->where('name', 'LIKE', "%$search%");
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement