How to pass parameter to Laravel DB::transaction()
The use
keyword is what you need:
$id = 3;DB::transaction(function($id) use ($id) { DB::table('users')->where('id', '=', $id)->get();});
For PHP 7 (untested, edited as requested by the answer below):
$id = 3;DB::transaction(function() use ($id) { DB::table('users')->where('id', '=', $id)->get();});
In PHP 7 the syntax has changed:
$id = 3;DB::transaction(function () use ($id) { DB::table('users')->where('id', '=', $id)->get();});
To answer @CaptainHypertext question of
If you alter $id inside the closure, will it affect the $id outside?
This method worked for me:
$id = 3;$transactionResult = DB::transaction(function($id) use ($id) { $request_id = DB::table('requests')->insertGetId([ 'company_id' => $company->$id, ]);return $request_id ;});echo($transactionResult);