2

How can use variable in laravel query builder. Here is my code.

$role = 1;
$user = DB::table('users')
                    ->join('assigned_roles', function($join)
                    {
                        $join->on('users.id', '=', 'assigned_roles.user_id')
                             ->where('assigned_roles.role_id', '=', $role );
                    })
                    ->get();

But it return Undefined variable: role. How can I solve this problem. Help me plz.

1 Answer 1

12

You need to import variables from the local scope to the anonymous function's scope:

function ($join) use ($role) {}

See the example in the docs.

Sign up to request clarification or add additional context in comments.

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.