Reputation: 75
I'm trying to make a search feature on laravel. now I'm using this query:
$products = Product::with(['category', 'store'])
->when($keywords, function ($query) use ($keywords) {
$query->where('name', 'LIKE', '%' . $keywords . "%")
->orWhere('description', 'LIKE', '%' . $keywords . '%');
})->get()
The problem is, say on the database i've a product with the name corrupti
, If i searched by the exact name or removed a character from beginning or end it works fine, but if I changed a single character it returns an empty list.
Users are likely to make typos, so I want to be able to find the product is the user typed corrupta
, corrupi
instead of corrupti
.
I know this is not a simple task to achive, I googled many things but I didn't find a solution.
One thing I've came accross is the php similar_text
funciton, it may be useful but I didn't find a way to include it in the database query.
Upvotes: 1
Views: 1887
Reputation: 1
try this:
$query = Product::query();
$searches = explode(' ', $request->query('q'));
if (isset($searches)) {
foreach ($searches as $search) {
$query->where(function ($q) use ($search) {
$q->where('code', 'ilike', '%' . $search . '%')
->orWhere('name', 'ilike', '%' . $search . '%');
});
}
}
$data = $query->get();
return ([
'success' => true,
'response' => $data,
'message' => 'Your message here'
]);
Upvotes: 0
Reputation: 856
https://www.php.net/manual/en/function.soundex.php https://www.php.net/manual/en/function.metaphone.php
Upvotes: 1