11

How can I do a Like-query, with multiple values to search for?

$searchWords = explode(' ', Input::get('search'));

Then I get an array of words that were given for the search.

How can I pass it in this:

$pages = Page::where('content', 'LIKE', '%'.$singleWord.'%')->distinct()->get();

A loop can't work, then it overwrites the $pages always; then it keeps always the latest search:

foreach($searchWords as $word){
    $pages = Page::where('content', 'LIKE', '%'.$word.'%')->distinct()->get();
}

2 Answers 2

28

A loop is the solution but you only need to add the where condition without executing the query

$pages = Page::query();
foreach($searchWords as $word){
    $pages->orWhere('content', 'LIKE', '%'.$word.'%');
}
$pages = $pages->distinct()->get();
Sign up to request clarification or add additional context in comments.

4 Comments

Can you use ->toSql() instead of ->get() and show me the return value?
It works, you must be using keyword that returns all pages, that's all.
added trim() to the searchword ;-)
trim() is the key to haven.
8

i will code it for you :

$pages = Page->where(function($query) use($word){

foreach($searchWords as $word){
    $query->orWhere('content', 'LIKE', '%'.$word.'%');
}

})->get();

you can try that , i hope that will help :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.