How to make my SQL query look for several words in a sentence, even if they do not follow each other

I have an SQL query for my search form.

$term = $request->get('term'); $queries = Article::where('title', 'LIKE', '%' . $term . '%')->published()->get(); 

My research works. If I have an article called “My wonderful article is awesome” and what I write in my search form “Welcome article”, it works.

But if I write an article “terrific”, the words will not follow each other, and this will not work.

How can I make my request work only with keywords?

thanks

+5
source share
3 answers

You can do something like the following:

 $term = $request->get('term'); $keywords = explode(" ", $term); $article = Article::query(); foreach($keywords as $word){ $article->orWhere('title', 'LIKE', '%'.$word.'%'); } $articles = $article->published()->get(); 

If you only want results that contain all the words in the query, just replace orWhere with where .

If you want to filter out specific words, you can add something like:

 $filtered = ["a", "an", "the"]; $filteredKeywords = array_diff($keywords, $filtered); 

Alternatively, you can pass closure if you want more dynamically:

 $filteredKeywords = array_filter($keywords, function($word) { return strlen($word) > 2; }); 
+8
source

why don't you try something like that

 $search = "article awesome"; $search = preg_replace("#\s+#", '%', $search); 

replacing spaces with "%" will resolve the case you mentioned

+1
source

if you want the search to ignore words whose order should work

 $search = trim(" article awesome great "); $search = preg_split("#\s+#", $search); $where = "WHERE column like '%" . implode( "%' AND column like '%", $search ) . "%'"; 

however, the server will require more runtime and resources,

also consider adding some escaping to avoid sql syntax errors

0
source

All Articles