This package will help you for this kind query. https://github.com/TomLingham/Laravel-Searchy
Laravel 5.3 Filter search results based on most matches
I am new to Laravel and I managed to make a search engine which is working. And now I want to improve it.
$search = $request['search'];
$searchValues = preg_split('/\s+/', $search); // split on 1+ whitespace
$results = Product::where(function ($q) use ($searchValues) {
foreach ($searchValues as $value) {
$q->orWhere('name', 'like', "%{$value}%");
}
})->get();
The problem: I have three rows in my table, one with the name foo, one with the name bar, and one with the name foo bar. They were created and put into my table in that order. Now, if I search for "foo bar", the first two results I get will be foo and bar (because they are fist in my table to match either foo or bar), and my third result will be foo bar. How can I make this search so it orders the results based on the number of keywords which are matched? So foo bar will be the first result.
Please or to participate in this conversation.