Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Like Eloquent with array value?

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();
}
like image 234
user1469734 Avatar asked Dec 29 '14 21:12

user1469734


2 Answers

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();
like image 171
lukasgeiter Avatar answered Nov 06 '22 23:11

lukasgeiter


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 :)

like image 43
Aouidane Med Amine Avatar answered Nov 06 '22 22:11

Aouidane Med Amine