Create a View inheritance in Laravel

Tag: Laravel v4.0+

Confession time - I wrote a "book". Yes, me too. Actually, I call it an "ePamphlet", and it is only about 8-10 pages, completely FREE, and written very narrowly about the Laravel Collection class. Laravel Collections Unraveled is just a deep dive into the class that I thought was too long for a blog post, and could be best presented via a LeanPub eBook. We'll dig into the source code of this popular class and see some use cases for the major functions.

Often times - for example, with index page lists - we have virtually the same blade for all of our models. "Virtually" all is the key word - because of course, a few will have some small differences. The temptation is to start adding conditionals, but we all know what a mess that can quickly turn into.

For one recent project what I did was this: all models used the same blade, but each also had its own sub-directory where I could "override" that view with one specific to the model. However, it was nice to be able to make a generic check in a BaseController::index() function, so I did it like this:

The directory structure was like this:

/views /objects /mymodel /index.blade.php /mymodel2 /create.blade.php index.blade.php

There is a single index.blade.php for ALL the objects' index() functions. I pass in the data into a fairly generic table, along with title or other specific information that every index will have.

My controllers are actually all inherited from a BaseController, so each is given a few class-wide variables such as $model but I don't need to create all the RESTful controller functions except where I need to override. So MyController won't have its own index() function, for example.

Here's where we allow the overriding of views. In the BaseController index() I put the following:

$view = (\View::exists('objects.'.$this->model.'.index')) ? 'objects.'.$this->model.'.index' : 'objects.index'; return View::($view);

The logic is simple. For the case of MyController, I have set $model = 'mymodel'. The View::exists will look in 'views/objects/mymodel/' for an index.blade.php, find it, and so use that customized version. For MyController2 (with 'mymodel2') it will look for it, *not* find it, and so use the main file.

Pretty dead simple, actually, and will save you a ton of boilerplate. (And yes, I know it isn't actually "inheritance" but I thought that word best gave an idea of what this was about).

Hope that helps!