Laravel’s view composers

Most websites contain parts that are visible on every single page. For example, a header with company logo and a footer with links to FAQs or general conditions are very common.
To avoid repetion of code (according to the DRY principle, don’t repeat yourself), a master view is created which contains all these fixed items, and has room for the dynamic content of each page.

Such a setup works quite well, but what if you would like to show some dynamic information in one of the fixed parts? For example, when a user has loggedin into your webapplication, it would be nice to show something like ‘Welcome firstname lastname’ at the top of each page. Or when a user has added a product to his shopping cart, the user likes to see the total number of items in his cart in the top bar.

Laravel has a model-view-controller setup, so all information that you want to show in a view, must be send from a controller to a view. In the examples above, this would mean that for every single page, the corresponding controller should send the user’s name to the master view. Of course, this would be very tedious. Fortunately, the Laravel framework has view composers, which can be used to make sure that certain dynamic content is available in each view.

First, we make a small adjustment in the masterview. We move the topbar that contains the sentence ‘Welcome firstname lastname’ to a partial view and we include the partial in the master view like so:


Next, open the AppServiceProvider in the folder app/Providers. This service provider contains two methods: boot and register. We will use the first one to send data to the topbar.

Include the following code inside the boot method:

   // write your code to get the dynamic data you want to show eg
   $user = \Auth::user();


Now the variable $user will always be available in the topbar partial. Although this is a very simple example, it nicely illustrates the possibilities.

When you have a lot of partial views that always need dynamic information, you may want to put the view composers in a separate service provider to keep your code organized. It is possible to create your own service provider and this will be discussed in an upcoming blog.

Mijn Twitter profiel Mijn Facebook profiel
Leonie Derendorp Webdeveloper and co-owner of PLint-sites in Sittard, The Netherlands. I love to create complex webapplications using Laravel! All posts
View all posts by Leonie Derendorp

Leave a Reply

Your email address will not be published. Required fields are marked *