php - Transactions and Eloquent -


i want use transactions in laravel application. however, struggle use them eloquent.

$user = $this -> auth -> user();  db::transaction(function() {     $stores_amount = $user -> stores() -> count(); #error }); 

i "undefined variable: user" error. problem , how can use select statements in eloquent transactions correctly?

$user isn't in scope inside callback

$user = $this->auth->user();  db::transaction(function() use ($user) {     $stores_amount = $user->stores()->count(); }); 

edit

$stores_amount scoped inside of callback. if need $stores_amount value out of transaction, can declare , scope callback well, reference:

$user = $this->auth->user(); $stores_amount = 0; db::transaction(function() use ($user, &$stores_amount) {     $stores_amount = $user->stores()->count(); });