39

From the laravel documentation: Database Transaction. It says that:

DB::transaction(function() {
    DB::table('users')->update(array('votes' => 1));
    DB::table('posts')->delete();
});

Here, 1 is explicitly entered to update the users... I tried this using a variable,

$id = 3;
DB::transaction(function() {
    DB::table('users')->where('id','=',$id)->get();
});

It throws an error:

Undefined variable: id

I also tried to place to $id as a parameter like this:

$id = 3;
DB::transaction(function($id) {
    DB::table('users')->where('id', '=', $id)->get();
});

Still, an error:

Object of class Illuminate\Database\MySqlConnection could not be converted to string

Have I done anything wrong? Please advise. Thanks...

LF00
  • 27,015
  • 29
  • 156
  • 295
Melvin
  • 5,798
  • 8
  • 46
  • 55

3 Answers3

83

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();
});
Alexandre Danault
  • 8,602
  • 3
  • 30
  • 33
  • 9
    Recommended lecture: [Anonymous Functions: Closures & Scoping](http://www.php.net/manual/en/functions.anonymous.php) – Rubens Mariuzzo Jun 13 '13 at 15:28
  • If you alter $id inside the closure, will it affect the $id outside? – Captain Hypertext Jun 24 '15 at 00:39
  • 3
    @CaptainHypertext Not necessarily, if you want to alter the outside $id, you can just reference it like so: `DB::transaction(function($id) use (&$id) {` – S.A May 06 '16 at 03:21
  • @Alexandre Danault It would be worth editing this answer reflecting the changes made in PHP 7 (mentioned in the other answer below.) – 1000Nettles Dec 24 '18 at 01:06
  • In PHP 7 you do not need $id to be placed inside function(). Instead simply pass it inside use() closure. That should be good enough to make the variable available inside the code block. – Dibyendu Mitra Roy Oct 21 '19 at 21:32
22

In PHP 7 the syntax has changed:

$id = 3;
DB::transaction(function () use ($id) {
    DB::table('users')->where('id', '=', $id)->get();
});
o.v
  • 835
  • 10
  • 15
  • This is clutch. – niczak Jun 26 '18 at 20:55
  • 1
    This is the new correct answer. I had the following error "Cannot use lexical variable $varName as a parameter name" and this answer did the trick. I even updated my composer to update the guzzle to see if it was the issue. – xWaZzo Feb 10 '19 at 19:36
2

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);
LeRoy
  • 4,189
  • 2
  • 35
  • 46