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...

3 Answers 3

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();
});
5
  • 9
    Recommended lecture: Anonymous Functions: Closures & Scoping Jun 13, 2013 at 15:28
  • If you alter $id inside the closure, will it affect the $id outside? Jun 24, 2015 at 0: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 6, 2016 at 3:21
  • @Alexandre Danault It would be worth editing this answer reflecting the changes made in PHP 7 (mentioned in the other answer below.) Dec 24, 2018 at 1: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. Oct 21, 2019 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();
});
2
  • This is clutch.
    – niczak
    Jun 26, 2018 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, 2019 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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.