Answer the question
In order to leave comments, you need to log in
How to improve the search on the site?
Friends, tell me. Wrote a search. For example, we have an article in the "Lorem ipsum 2" database. If I enter
the letters from the title in order, then the article is returned, and if, for example, "Lorem 2", then it is not returned. How to make it come back?
$('.search-field').on('keyup', function(){
var words = $(this).val().trim();
$.ajax({
url: "/search",
type: "post",
data: {words: words},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(results) {
$.each(results, function(key,result){
$('.search-results > div > a').text(result.title)
})
}
})
})
public function search()
{
$words = Request::get('words');
$results = Articles::where('title', 'LIKE', '%' . $words . '%') -> get();
return $results;
}
Answer the question
In order to leave comments, you need to log in
Break the search word by spaces and look for the occurrence of each element using AND, OR, and the %...%.
AND or OR it is up to you to decide how inaccurate it will show the results
. If it is AND, then it will find articles with lorem and 2 in the text. (Both are present)
If there is an OR, it will find everything with lorem and everything with 2 (That is, only one or the other)
public function search()
{
$items = explode(" ",Request::get('words'));
$Articles = new Articles();
foreach ($items as $item){
$Articles->where('title', 'LIKE', '%' . $words . '%')
// $Articles->orWhere('title', 'LIKE', '%' . $words . '%') тут как хотите
}
$results = $Articles -> get();
return $results;
}
No need for bicycles, working package:
https://github.com/nicolaslopezj/searchable
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question