Support the ongoing development of Laravel.io →
Database Eloquent Views

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

Last updated 2 years ago.
0

You should pass $data to closure by reference:

DB::transaction(function() use ($user, &$data)
0

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

0

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

0

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

0

Sign in to participate in this thread!

Eventy

Your banner here too?

LukasMa lukasma Joined 26 Nov 2014

Moderators

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

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.