Reputation: 433
I've read several similar posts and I tried them, but still it doesn't work for my site.
When I search a word "think" the search result shows "I think this is it". However, when I search "I think" the result is "0 match found".
So to achieve multiple words search, I did below:
Controller.php
$keyword = "I think"
$words = explode(' ', $keyword);
$data = Post::where(function ($query) use ($words)
{
foreach($words as $word){
$query->where('example', 'LIKE', '%' . $word . '%');
}
})->get();
However, result is same. "think" shows results. "I think" doesn't hit any results.
also debugged with dd($data)
// $keyword = "think"
"select * from `posts` where (`example` LIKE ?)"
// $keyword = "I think"
"select * from `posts` where (`example` LIKE ? and `example` LIKE ?)"
So what would be wrong? Thank you.
[Additonal info (Edited)]
$bindings = $query->getBindings();
dd($bindings);
// array:2 [▼
0 => "%I%"
1 => "%think%"
]
Upvotes: 0
Views: 1506
Reputation: 43
$users = User::where(function ($query) use($userSearch) {
$searchWords = explode(' ', $userSearch);
$query->where('name', 'like', '%'.$searchWords[0].'%');
for($i=1;$i<count($searchWords);$i++) {
$query->where('name', 'like', '%'.$searchWords[$i].'%');
}
})->get();
Upvotes: 0
Reputation: 433
SOLVED
It was my bad. On my blade.php, there was a line
@if (preg_match("/^[0-9a-zA-Z]*$/",$keyword))
this regex didn't have space, that's why it didn't work. so just changed to:
@if (preg_match("/^[0-9a-zA-Z ]*$/",$keyword))
then totally it worked.
Thank you for helping teachers.
Upvotes: 0
Reputation: 72
I would suggest using Laravel scout for this. But alternatively, to do a fuzzy text search in sql. Or... assuming we don't use MYSQL match features, and we were to use a laravel eloquent. 1) Split the string. 2) use query builder.
$words = explode(' ', $searchString);
$results = Post::where(($q) use ($words) {
$firstWord = array_shift($words);
$q->where('example', $firstCase);
foreach($words as $word) {
$q->orWhere('example', $word);
}
})->get();
Upvotes: 1