Order by best match in eloquent

Viewed 1496
2 Answers

Yes as suggested, you can use orderByRaw() So your query would be transformed Like:

$result = Product::where("ProductCode", "LIKE", '%200%')
                ->orderByRaw('CHARINDEX('200', ProductCode, 1) DESC, ProductCode ASC')
                ->get();

Here, it supposed, the model name is Product for table products.

We can use raw query to order by best match. Its given me best match results.

DB::select(
    "SELECT *
       FROM  table_name
       WHERE column_name LIKE '%".$search_word."%' 
       ORDER BY
        CASE
        WHEN column_name LIKE '".$search_word."' THEN 1
        WHEN column_name LIKE '".$search_word."%' THEN 2
        WHEN column_name LIKE '%".$search_word."%' THEN 3
        WHEN column_name LIKE '%".$search_word."' THEN 4
        ELSE 5
    END")

The matched result will be sorted by the below order.

  • First Case: Exact match with search word.
  • Second Case: Starting with search word.
  • Third Case: Search word in any position.
  • Fourth Case: Ending with search word.
  • ELSE Case: Search word does not contains.
Related