I'm running Laravel 5 and have built a small search function:
$q = Input::get('q'); $search_terms = explode(' ', $q); $user_query = User::select(); $news_query = Article::select(); foreach ($search_terms as $term) { $user_query->where('username', 'like', '%' . $term . '%'); $news_query->where('title', 'like', '%' . $term . '%'); } $user_results = $user_query->get(); $news_results = $news_query->get(); return view('search', ['q' => $q, 'user_results' => $user_results, 'news_results' => $news_results]);
It works for one search term, but doesn't quite work with multiple words.
Example:
- "boss" returns users and news items that contain "boss"
- "boss man" returns users and news items that contain "boss"
- "man boss" returns users and news items that contain "man"
How can I make adjustments so it will return users and news items that contain "boss" or "man" ?
-------------Problems Reply------------
Right now, your query is executed using and
statements, so MySQL is looking for usernames consisting of both boss
and man
.
You can change to orWhere()
and it should work right away. Here's a quick experiment I did in Tinker using your code:
$terms = explode(' ', 'c a');
$user_query = User::select();
foreach ($terms as $term) {
$user_query->orWhere('username', 'like', '%' . $term . '%');
}
$user_results = $user_query->get();
$user_results->toArray();
// array(
// 0 => array(
// 'id' => 2,
// 'username' => 'christopher',
// 'created_at' => '2014-04-27 18:41:56',
// 'updated_at' => '2014-11-07 13:42:58',
// 'remember_token' => NULL
// ),
// 1 => array(
// 'id' => 4,
// 'username' => 'Kalle',
// 'created_at' => '2014-11-07 13:42:55',
// 'updated_at' => '2014-11-07 13:42:55',
// 'remember_token' => NULL
// )
// )