Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 931
Melvin Avatar asked Jun 13 '13 10:06

Melvin


1 Answers

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(); }); 
like image 118
Alexandre Danault Avatar answered Oct 07 '22 20:10

Alexandre Danault