Back

Transactions in Laravel 5


Hi, I have trouble with a transaction. I want to improve a dashboard view in my applicaton. To do so, I want to do a transaction in my DashboardController with multiple queries and pass the data I got from the DB to the dashboard view. I thougth this should look somethink like this:

$data = [];

DB::transaction(function() use ($user, $data)
{
	$data = [
		'bookings_count' => $user -> bookings() -> count(), 
	];
});

return view('dashboard', $data);

But I always get an "undefined variable" error when trying to access the dashboard view: "Undefined variable: bookings_count (View: C:\lamp\www\chargio\resources\views\dashboard.blade.php)". I use blade like this:

{{ $bookings_count }}

Works without problems if I remove the transaction stuff. But without a transaction... How can I make the code above work???

Thanks, Micheal

Xum replied 4 years ago

You should pass $data to closure by reference:

DB::transaction(function() use ($user, &$data)
beanmoss replied 4 years ago

Why do you need to use Transaction? I think a better implementation for this is:

View::composer(array('profile','dashboard'), function($view)
{
    $view->with('count', User::count());
});

L5: http://laravel.com/docs/5.0/views#view-composers L4: http://laravel.com/docs/4.2/responses#view-composers

LukasMa replied 4 years ago

@beanmoss This is just an example. I run like 10 queries and thought it would be nice to commit them in one single transaction?!

amcuserguy replied 3 years ago

i encountered the same problem too. @MichealMi, did you found a solution?


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us