N
N
Nikita Dergachov2017-07-31 14:03:11
Laravel
Nikita Dergachov, 2017-07-31 14:03:11

How to pass a variable to join?

Have a request

DB::table('users')
        ->join('contacts', function($join)
        {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);
        })
        ->get();

I want to pass the value of a variable to the condition
$id = 5;
DB::table('users')
        ->join('contacts', function($join)
        {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '=', $id);
        })
        ->get();

But inside the anonymous function, the value of this variable is not visible. How to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Koch, 2017-07-31
@vanillathunder

Use use :

function($join) use ($id){
  $join->on('users.id', '=', 'contacts.user_id')
    ->where('contacts.user_id', '=', $id);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question