Passing a Closure with a variable to where method in Laravel query builder
Asked Answered
H

1

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?

Hereabout answered 3/9, 2020 at 9:15 Comment(0)
O
8

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();
Octopus answered 3/9, 2020 at 9:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.