Reputation: 113
I would like to write search query that uses supplied phrase to search a table, return the value that matches any part of the phrase. this code is working, but results are nothing. For example, table have 'abcde', and I searched 'bcd', result is nothing.
protected function fullTextWildcards($term)
{
return str_replace(' ', '*', $term) . '*';
}
public function index(Request $request, $slug = null)
{
$query = $slug
? \App\Tag::whereSlug($slug)->firstOrFail()->articles()
: new \App\Article;
if ($keyword = request()->input('q')) {
$raw = 'MATCH(title,content) AGAINST(? IN BOOLEAN MODE)';
$query = $query->whereRaw($raw, [$this->fullTextWildcards($keyword)]);
}
$articles=$query->latest()->paginate(10);
return view('articles.index',compact('articles'));
}
How to chain everything together so I achieve the desired result?
Thanks in advance.
Upvotes: 0
Views: 2254
Reputation: 1322
You can just use like
in your query to get any matches in a given column. Try this:
public function index(Request $request, $slug = null)
{
$filter = ['keyword' => $request->q , 'slug' => $slug];
$articles = \App\Tag::where(function ($q) use ($filter){
//you can leave this I just put the so the code seems clean
if ($filter['slug'] !== null) {
$q->whereSlug($slug);
}
if ($filter['keyword']) {
$keyword = $this->fullTextWildcards($filter['keyword']);
//you can use **like** this
$q->where('title', 'like', "%".$keyword."%")->orWhere('content', 'like', "%".$keyword."%");
}
})->latest()->paginate(10);
return view('articles.index',compact('articles'));
}
Hope this helps
Upvotes: 3