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.

<?php
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!

Further Reading