Laravel – Using View Creators to Make Default Values

What is a “View Model”?

In web MVC architecture, there are scenarios you run into where you’d like the same set of dynamic information passed into each view, but that view isn’t called from one location. One such example is a menuing system. The items you pass into the navigation might potentially always be the same set of items, but the controller rendering that View or partial might not always be the same one.

A View Model looks to solve this problem by simply saying “when this view gets run, inject these values”.

Laravel View Models

In Laravel, there are a couple terms you’ll want to learn about; these include “View Composers” and the lesser known “View Creator”. These are two types of View Model that Laravel provides. A “View Composer” will be run when a view is rendered, and a “View Creator” will be run when a view is instantiated. The difference may not be evident at first glance, but it’s actually really important.

A situation where you might want to use one of these is for default values in a view, like the text that goes in the <title></title> tags. In the past, I’ve always put some logic in the View to detect whether a value is present or not, usually by writing <title>{{ !empty($title) ? $title : "Default Title" }}</title>.  If you’re using that value once, then maybe this isn’t a bad idea, but what happens if you need to use that variable about 15 times? It gets to being quite tedious and tiresome.

My First Attempt: The Composer mentions the Composer first and covers it quite in-depth, so I thought that maybe it would be a good candidate for the job. It turns out, though, that it doesn’t work. The callback is ran when the View is rendered, which is way after the View is instantiated. The information you pass to the View via ->with() is overridden by the variables set in the View Composer.

My Second Attempt: The Creator

So I got to thinking, “The Composer is being called after the View is being returned, so what about the Creator? Is that the difference?” Well, it turns out that it is; from the documentation:

View creators work almost exactly like view composers; however, they are fired immediately when the view is instantiated.

What does that mean? Well, the callback that you define with the Creator is called immediately after View::make() , which is before any ->with()s.  This enables us to set a default value for the View and then override it when the View is called, if desired.

Leave a Reply

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

Thanks for your thoughts!