I have a SQL query for my search form.
$term = $request->get('term');
$queries = Article::where('title', 'LIKE', '%' . $term . '%')->published()->get();
My research is working. If I have an article called "my great article is awesome" and that I write in my search form "greate article" it works.
But if I write "article awesome", the words do not follow each other, and it does not work.
How do I get my query to work just with keywords?
Thank you
Use the SUBSTRING() function. The first argument is the string or the column name. The second argument is the index of the character at which the substring should begin. The third argument is the length of the substring.
The SQL LIKE Operator The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
CONTAINS is a predicate used in the WHERE clause of a Transact-SQL SELECT statement to perform SQL Server full-text search on full-text indexed columns containing character-based data types. CONTAINS can search for: A word or phrase. The prefix of a word or phrase.
You can do something like follows:
$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 want only results that contain all the words in the query just replace the orWhere
with where
.
If you want to filter out certain words you could add something like:
$filtered = ["a", "an", "the"];
$filteredKeywords = array_diff($keywords, $filtered);
Alternatively you can pass a closure if you want to be more dynamic:
$filteredKeywords = array_filter($keywords, function($word) {
return strlen($word) > 2;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With