DEV Community

Elvis Pestana
Elvis Pestana

Posted on • Originally published at Medium on

Adventures in Laravel 5.4 land — view management

update: This also works fine in Laravel 5.5

Recently started working with Laravel (5.4) and so far it’s been a joy to work with.

The first roadblock I encountered was on how to organize views/templates.

Page templates

I went down the simplicity path, having the following rules:

  1. Grab the controller name, exclude the Controller part of the name, put it to lowercase. With this we have a folder that will house the templates that are used by that controller. For example: HomeController > Home > home.
  2. Let’s assume that we create a method inside HomeController whose job is to load a generic about us page. So we create the method aboutUs and call the relevant view. What’s the name of view? Just call it about-us , which means a path /resources/views/home/about-us.blade.php.
  3. The default controller method has a special name, __invoke, and since I did not want to have a view called invoke.blade.php I decided to just use the same name of the controller. So for now we have a folder called home with a file called home.blade.php. Based on these rules we can immediately assume, with a high degree of certainty, that the view home.blade.php is called inside HomeController::__invoke.

What about partials?

Partials are blocks of code that are reused in more than one page/view, so I needed a set of rules for creating these, so that the location where they exists makes sense and gives an ideia of how it’s used. These rules assumed you are following the previously laid out rules.

  1. When the partial is only used among the views of a single controller, create a folder called partials inside the controller view folder. Put your partials in these. Ex: /resources/views/home/partials/example-partial.blade.php.
  2. When the partial is used by different controllers, then put them inside a partials folder inside the views folder, on the same level as the controller views folder. Ex: /resources/views/partials/example-partial.blade.php.

Layouts

I did not see a reason to change the location of layout files (/resources/views/layouts/master.blade.php).

I’m sure there will be edge cases in which these rules cannot be applied, but I hope that these rules minimize those cases, instead of having the mess of view files that makes it hard to pinpoint what are it’s intended uses.


Top comments (0)