2

Using Laravel's query builder example is it possible to pass a variable to this function:

$someVariable = 1;

DB::table('users')
        ->where('name', '=', 'John')
        ->orWhere(function ($query) use ($someVariable) {
            $query->where('votes', '>', $someVariable)
                  ->where('title', '<>', 'Admin');
        })
        ->get();

It seems the function cannot access the variable outside of itself. I get an error: Undefined variable: $someVariable

2
  • " I get an error. " how about telling us what the error is? Commented Sep 26, 2017 at 21:33
  • @rtfm updated with error Commented Sep 26, 2017 at 21:34

2 Answers 2

10

You'll need to use the "use" keyword after your function, for variables outside of that function. If $someVariable is the one you want to use, this should work.

$someVariable = 1;

DB::table('users')
->where('name', '=', 'John')
->orWhere(function ($query) use($someVariable) {
    $query->where('votes', '>', $someVariable)->where('title', '<>', 'Admin');
})->get();
Sign up to request clarification or add additional context in comments.

Comments

0
use Superglobals 

$GLOBALS["someVariable"] = 1;
DB::table('users')
->where('name', '=', 'John')
->orWhere(function ($query) {
       $query->where('votes', '>', $GLOBALS["someVariable"])
       ->where('title', '<>', 'Admin');
})
->get();

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.