Tag: Laravel v4.0+
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!