I have started using Laravel’s View Composers which come in handy when you have a navigation bar that constantly needs certain data. For example, you have an ecommerce store and you need to poll how many items a user has in their basket on pretty much every page they move onto, or you need a login/register button when a user isn’t logged in and then a profile options button when they are.

You could be really lazy and add the same code/query into every single controller, which yes, that will work, but then that’s not DRY (Don’t Repeat Yourself). To fix this, we can complete a couple of simple steps and have one bit of code which will constantly be in use every time a certian partial is called.

If you currently have a layout/template view which has the navigation menu already written in, then you will need to move this out into a partial. Within your “resources > views” directory, you will need to create a new directory called “partials”. Once done, you will need to create a “nav.blade.php” file and paste in your navigation code. It should look something like this…
“`


“`
Next, in your layout or template blade, you can add…

require(‘partials.nav’)
o
This will include your navigation file.

Now for setting up the View Composer, firstly we need to setup a ServiceProvider (for the sake of this tutorial I will show a example for counting a basket)…

ocomposer(
o’partials.nav’, ‘AppHttpViewComposersBasketComposer’
o);
o}
o
o/**
o * Register the service provider.
o *
o * @return void
o */
opublic function register()
o{
o//
o}
o}
o
The service provider will run whenever you use the nav partial and in the next attribute, it will use your BasketComposer which should look something like this…

ocart = Cart::Contents();
o}
o
o/**
o * Bind data to the view.
o *
o * @param View $view
o * @return void
o */
opublic function compose(View $view)
o{
o$view->with(‘cart’, $this->cart[‘result’][‘total_items’]);
o}
o}

Obviously, depending on your API or personal use, your code should vary here, but you should get an idea of how this is working. Everytime we need the nav partial, the view will be rendered with our given items. This can also be passed to many views at once which makes it work really well. I also believe you can pass many different constant data sets into a single view, so you could in theory also add a user constant for log in and edit profile data.

For more information, feel free to visit Laravel’s documentation on [View Composers](https://laravel.com/docs/5.2/views#view-composers) and this nice [Laracasts video](https://laracasts.com/series/laravel-5-fundamentals/episodes/25) which helped me figure out how to use it correctly.

If you have a unique use case, please let me know and we can discuss as a community just how useful these View Composers are.


Leave a Reply

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

%d bloggers like this: