5

According to the Laravel documentation, an 'or' condition can be grouped by passing a Closure as the first argument to the orWhere method:

$users = DB::table('users')
        ->where('votes', '>', 100)
        ->orWhere(function($query) {
            $query->where('name', 'Abigail')
                  ->where('votes', '>', 50);
        })
        ->get();

What I wanted is use a variable inside the query, which will look like:

$q = $request->get('query');
$users = DB::table('users')
            ->where('votes', '>', 100)
            ->orWhere(function($query) {
                $query->where('name', $q)
                      ->where('votes', '>', 50);
            })
            ->get();

I tried to pass it as a second argument, like:

$q = $request->get('query');
$users = DB::table('users')
            ->where('votes', '>', 100)
            ->orWhere($q, function($query, $q) {
                $query->where('name', $q)
                      ->where('votes', '>', 50);
            })
            ->get();

But it is not working, any help?

Ayenew Yihune
  • 1,059
  • 13
  • 19

1 Answers1

7

you need to use use() function to pass data into closer ref link In PHP, what is a closure and why does it use the "use" identifier?

 $q = $request->get('query');
 $users = DB::table('users')
          ->where('votes', '>', 100)
          ->orWhere(function ($query) use($q) { //  use function to pass data inside
                $query->where('name', $q)
                    ->where('votes', '>', 50);
           })
           ->get();
Kamlesh Paul
  • 11,778
  • 2
  • 20
  • 33