Reputation: 1773
I want to use transactions in my laravel application. However, I struggle to use them with Eloquent.
$user = $this -> auth -> user();
DB::transaction(function()
{
$stores_amount = $user -> stores() -> count(); #Error
});
I get an "Undefined variable: user" error. What is my problem and how can I use SELECT statements in Eloquent with transactions correctly?
Upvotes: 1
Views: 387
Reputation: 212502
$user
isn't in scope inside your callback
$user = $this->auth->user();
DB::transaction(function() use ($user) {
$stores_amount = $user->stores()->count();
});
EDIT
$stores_amount
is only scoped inside of the callback. If you need to get the $stores_amount
value out of the transaction, then you can declare it and scope it into the callback as well, but by reference:
$user = $this->auth->user();
$stores_amount = 0;
DB::transaction(function() use ($user, &$stores_amount) {
$stores_amount = $user->stores()->count();
});
Upvotes: 4