1

I want to search for specific word instead of letter from a table. Right now i'm using like but it not like expected:

//  Category Table
-----------------------------------------------------
| id       |   amount           |  updated_at       |
+----------+--------------------+-------------------+
| 1        | Bread              |2016-02-10 13:17:29|  
| 2        | Bread Loaf         |2016-02-10 13:17:29|
| 3        | Bread1             |2016-02-10 13:17:29|
+----------+--------------------+-------------------+

For example I search for word "bread":

$words = "bread";
$query = Category::where(function ($query) use ($words) {
              $query->where('name', 'like', '%' . $words . '%');
         })->get();

The result: all bread is coming out.

What I expected is "Bread1" is not get query. Only Bread and Bread Loaf.

What should I add to my query?

ssuhat
  • 7,387
  • 18
  • 61
  • 116
  • 2
    You may want to try this SELECT * FROM products WHERE product_name RLIKE "[[:<:]]bread[[:>:]]"; [Same Question Here](http://stackoverflow.com/questions/5743177/mysql-how-to-search-for-exact-word-match-using-like) – John Roca Feb 10 '16 at 04:00
  • Essentially this is evaluated as `WHERE name LIKE '%bread%'` meaning it will match anything with bread in it. It doesn't evaluate it as a word. If you just added spaces, it would not match anything that starts or ends in bread. John Roca gave a good solution with regex. – Devon Bessemer Feb 10 '16 at 04:04
  • @JohnRoca thanks. it working – ssuhat Feb 10 '16 at 04:07
  • @SSuhat you can mark my answer as correct! – John Roca Feb 10 '16 at 04:13

2 Answers2

0

You may want to try this SELECT * FROM products WHERE product_name RLIKE "[[:<:]]bread[[:>:]]"; Same Question Here

Community
  • 1
  • 1
John Roca
  • 1,204
  • 1
  • 14
  • 27
0

In Laravel Eloquent you can do this like below.

$query->where('name', 'RLIKE ', "[[:<:]]"$words"[[:>:]]");

In raw query you can search it like this.

SELECT * FROM categories WHERE name RLIKE "[[:<:]]categoryNameHere[[:>:]]";
Hadayat Niazi
  • 1,991
  • 3
  • 16
  • 28