0

I'm trying to loop a query like the one in the title in laravel. Every cycle is a new "AND (x OR y OR z)" condition.

Here is what I have:

$offers = Offer::query();
foreach($values as $val){
    $offers->where('title', 'LIKE', '%'.$val.'%')
    ->orWhere('company', 'LIKE', '%'.$val.'%')
    ->orWhere('location', 'LIKE', '%'.$val.'%')
    ->orWhere('country', 'LIKE', '%'.$val.'%')
    ->orWhere('country_code', 'LIKE', '%'.$val.'%');
}
$offers->get();

However this doesn't do what I want.

I also tried this:

$offers = Offer::query();
foreach($values as $val)
{
    $offers->where(function($query, $val) {
        $query->where('title', 'LIKE', '%'.$val.'%')
        ->orWhere('company', 'LIKE', '%'.$val.'%')
        ->orWhere('location', 'LIKE', '%'.$val.'%')
        ->orWhere('country', 'LIKE', '%'.$val.'%')
        ->orWhere('country_code', 'LIKE', '%'.$val.'%');
    });
}
$offers = $offers->distinct()->get();

But this gives me an error at the $offers->where(function($query, $val) line: Missing argument 2 for App\Http\Controllers\OffersController::App\Http\Controllers\{closure}()

I could easily write the raw SQL query in the loop, but I really would like to use Laravel's ORM here.

Any idea how to achieve that? Thanks!

frsechet
  • 770
  • 5
  • 14
  • Take a look here http://stackoverflow.com/questions/16995102/laravel-4-eloquent-where-with-or-and-or – tacone Sep 14 '15 at 23:59
  • Thanks for the pointer, I also tried that before, but I get the following error: Missing argument 2 for App\Http\Controllers\OffersController::App\Http\Controllers\{closure}() – frsechet Sep 15 '15 at 00:10
  • That's a weird error, try to update your question with the code of that attempt. – tacone Sep 15 '15 at 00:14
  • oh, I just found what I did wrong: `function($query, $val)` should be `function($query) use ($val)`. I always forget about the "use"... – frsechet Sep 15 '15 at 00:19
  • Could you answer you own question with the solution you've found? – tacone Sep 20 '15 at 00:57

1 Answers1

-1

Of course, the answer was simple : $offers->where(function($query) use ($val) {...

:-)

frsechet
  • 770
  • 5
  • 14