1

I am facing a problem with my laravel app while using search functionality. Here is my code for search function

use DB;
public function search(Request $request){  
        $query = $request->input('query');
        $products = DB::table('products')
                    ->where('product_title','like','%'.$query.'%')
                    ->get();

Lets imagine I have product title as "Demo Product" in my app. There is no problem if I intend to search product with keyword like de/d/mo/pro etc.Those keywords showing some result. But how can I get search query result if I search with keyword like "deemoo"/"prooductt" etc [Intend to show "Demo Product"].Please give me some suggestion if you can.Thanks in advance :)

2

1 Answer 1

0

You need to use a full text search index in the database of your choice. You can read more on full text indexes for MySQL here.

To actually use the index with Laravels Eloquent you need to use a raw query.

User::whereRaw("MATCH(product_name)AGAINST('soccer' IN BOOLEAN MODE)")
    ->limit(10)
    ->get();

To make the syntax a bit nicer you can add a scope to your Product model.

public function scopeNameMatches($query, $searchTerm)
{
    return $query-> whereRaw("MATCH(product_name)AGAINST(? IN BOOLEAN MODE)", $searchTerm);
}

And you would use it by calling the scope in the following way.

Product::nameMatches("soccer")->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.