Using View Composers in Laravel 4
Sometimes a view will need a variable every single time it is loaded. Perhaps we are developing a system for tracking users, and we want to display the number of users registered in our system next to a button to display the list of users. If we have a resource controller for our User
model, we would have to pass a count of users on every method in that controller that displays a view, which is every single one! That isn't very DRY! Luckily, Laravel ships with a way to include this variable in every call to a particular view. We do this through the use of view composers.
Let's see how we might implement the behavior we outlined above.
View::composer('layouts.user', function($view)
{
$view->with('num_of_users', User::getUserCount());
});
Whenever the "layouts.user" view is loaded, the getUserCount()
function on the User
model will be fired, and the result is stored in the $num_of_users
variable. This variable will now be available in the "layouts.user" view. This lets us use the following code with confidence.
{{ link_to_route('user.index', 'All Users: ' . $num_of_users) }}
Damn, that was easy! Thanks, Laravel!
Written by Alex Sears
Related protips
4 Responses
Thanks a lot! Really helped me understand view composers.
Brilliant! I finally understand what a View Composer is!
nicely understood
Can I put the View::composer code inside a method of a controller?, i'm trying but the code inside is not running:
/**
* Controller method
*/
public function patientDetail($code){
// Obtain the patient
$thepatient = Patient::where('document', '=', $code)->first();
View::composer('test.alltests', function($view){
Log::info("In the patient composser");
$view->with('patient', $thepatient);
});
return View::make('patient.detail', compact('thepatient'));
}
Thanks.