Here is my code, it allows you to do a keyword search and it works well when searching on several "OR" words. However, I want to make the results more relevant. I would like the results to be sorted by the number of searched words they have. For example : The two words entered in a search are "blue" and "red". Well, I would like the records that contain "blue" AND "red" to be the first to be sorted. Here is my current code:
public function search()
{
$data = [
'title'=> $description = 'Recherche sur '.config('app.name'),
'description'=> $description,
'heading'=> config('app.name'),
];
$q = request()->input('q');
$words = explode(' ', $q);
$query = Product::query();
foreach ($words as $word) {
$query->orWhere('title','like',"%$word%")
->orWhere('subtitle','like',"%$word%")
->orWhere('description','like',"%$word%");
}
$products = $query->paginate();
return view('products.search', $data)->with('products', $products);
}
Can you please help me?
The answer here may help you: How to get and order the most relevant entries from the database with multiple keywords Laravel 5
But the answer there is not "perfect", because its only sorting per 25 records its not using the whole table.
You can use Laravel Scout, but you have some setting up to do. I suggest you start experimenting using Algolia or MeiliSearch driver here because those drivers have excellent smart searching.
Algolia This is NOT FREE, but there's a FREE TIER here if you exceed you will have to pay https://www.algolia.com/pricing/
Meilisearch This is Open source, you can install this on your own server.