Disable Views Cache

Unfortunately Laravel doesn't come with an option to disable views cache, even if you set the environment to local or enable debug. I have found this to be very disturbing for development, but I've managed to find a pretty elegant solution.

I have setup a group for all my routes and created a Middleware to pass every request through, so I can delete the cache between every request.

The code is pretty simple and you can see it below.

How to Disable Views Cache Before Every Request

First of all you will have to create a group where you will place all of your routes.

So this is how the router.php is going to look like:

// Checking if the environment is debug, because we don't want to disable cache in production
$middleware = [];
	array_push($middleware, ['middleware' => 'clearcache']);

// The route group that will pass every request to a Middleware
Route::group($middleware, function() {
	Route::get('/', '[email protected]');
	Route::post('/', '[email protected]');

Now you have to head over to kernel.php and a single line to the $routeMiddleware array. It will look like this:

protected $routeMiddleware = [
	'auth' => \App\Http\Middleware\Authenticate::class,
	'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
	'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
	'clearcache' => \App\Http\Middleware\ClearCache::class,

Now you have to create the actual Middleware that will take care of the views cache. I have created a file called ClearCache.php in App/Http/Middleware. Here's how it has to look:


namespace App\Http\Middleware;

use Closure;
use Artisan;

class ClearCache
	public function handle($request, Closure $next)
		return $next($request);

This Middleware will make sure that Laravel deletes views cache before any request, so you won't be annoyed by it during development.

Note: Don't forget to remove this code for production, because the views cache in Laravel is really useful. It can decrease page load significantly and reduce the resource usage of your server.

Thanks to James Elliott for helping me improve this.