Ayman Tarig
Ayman Tarig

Reputation: 75

Laravel: Search by similar string

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

Answers (2)

Marcos P. Pastor
Marcos P. Pastor

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

Hop hop
Hop hop

Reputation: 856

https://www.php.net/manual/en/function.soundex.php https://www.php.net/manual/en/function.metaphone.php

  1. use metaphone (or soundex) to encode words you want to be searchable
  2. put them in a database column say products.name_as_metaphone
  3. make your search function encode searched word to metaphone, then make it look in the metaphone column (and not in product.name)...
  4. profit

Upvotes: 1

Related Questions