Reputation:
Consider this route:
Route::get('/', function()
{
$categories = Category::all()->toHierarchy();
$stats = array(
'total_users' => User::all()->count(),
'total_services' => 5,
'total_orders' => 2,
'latest_service' => '1 hour ago'
);
return View::make('homepage')
->with('categories', $categories)
->with('stats', $stats);
});
But I need $categories and $stats in all views! I don't want to repeat db calls in every view or controller, how would I go about implementing this?
Upvotes: 1
Views: 971
Reputation: 1386
You can use simple:
View::share('data', $data);
View::make....
for passing variables to all views.
Upvotes: 0
Reputation: 153140
You're looking for View Composers. They allow you to run some code whenever a certain view (or all views via *
) are rendered.
View::composer('*', function($view){
$categories = Category::all()->toHierarchy();
$stats = array(
'total_users' => User::all()->count(),
'total_services' => 5,
'total_orders' => 2,
'latest_service' => '1 hour ago'
);
$view->with('categories', $categories)
->with('stats', $stats);
}
You can put this code in your app/filters.php
or create a new file app/composers.php
and include it by adding require app_path().'/composers.php';
at the end of app/start/global.php
Upvotes: 4