Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

princelionelnzi's avatar

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.

0 likes
2 replies
princelionelnzi's avatar

@ankitparmar372 Thanks you for this link. Based on the example given, I was able to write this code:

$results = Searchy::products('name')->query($search)->get();

In my product table, I have 3 rows: => first rows foo => second rows bar => third rows foo bar

When I search for foo bar using the fuzzy driver provided by Searchy, I can only find the third row and not the two first rows while they contain foo and bar. How can I make it and also order the results based on the most matches ?

Thanks in advance

Please or to participate in this conversation.