Melvin
Melvin

Reputation: 6008

How to pass parameter to Laravel DB::transaction()

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

Upvotes: 40

Views: 27547

Answers (3)

Alexandre Danault
Alexandre Danault

Reputation: 8682

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();
});

Upvotes: 85

o.v
o.v

Reputation: 885

In PHP 7 the syntax has changed:

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

Upvotes: 24

LeRoy
LeRoy

Reputation: 4466

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);

Upvotes: 2

Related Questions