How to compile Laravel Blade views on demand

During a CI/DI pipeline one of the common build stages is to minify the HTML.

To do this in Laravel, you may run gulp html minify to the location of the compiled views (by default storage/views).

You might think that that is all it takes, right? Well, it is not that easy. The reason for it is that the compiled views are outdated in many cases, and the user will see the old views.

The best solution would be first to clear all the current views and then compile all of them with the latest changes.

The first step is quite straightforward and can be done by the command provided by Laravel itself:

This article explains how to achieve the second step, compiling all the views  in the storage folder (or anywhere you specified) on demand.

I have created a console command for this purpose. The  code follows below:

Name the above file ViewCompileCommand.php and store it in the folder app/Console/Commands.

After that, register the command in the kernel.php at  app.Console.Kernel.php by adding it to the commands array.

It should look like:

Now that anything is setup, you can just run the following command in the console:

After that, and the views will get compiled into the storage folder.

I hope this tutorial was useful to your specific use case, and if not feel free to ask me in the comments for advice.

I could not find any information online on this topic and I had to  be creative and provide my own solution. This is why I am sharing it, just in case someone else needs it.

On the next tutorial I will post a solution on how to speed up Laravel drastically by caching the compiled views in Redis or some other memory store, instead of locally.

In my dating site, this technique decreased the response time from 1s to under 100ms.