Simple Cache buster for Laravel

Categories: Development, WordPress

Caching busting with Laravel is super simple. It comes with something called Mix ( or Elixer ) that handles front-end processing. Unfortunately, my front-end requirements have some specific needs that prevent me from taking advantage of Mix. The site uses Docker and is also behind a proxy cache so there wasn’t a simple way that I could reliably regenerate a hash for each Docker Deploy out of the box.

Mix does indeed have a way to version public assets but as I mentioned would not work in my situation.

I opted to add a task to my gulpfile.js that will generate a file in config/cacheBuster.php that simply contains a timestamp of the build and is returned in a Laravel Config file.

First you will need to install the File System package found here by typing npm install file-system --save

Next, add the following task to your Gulp build.

gulp.task('cacheBuster', function(cb){
    fs.writeFile('config/cacheBuster.php', '<?php return ' + new Date().getTime() + ';', cb);
});

You can call the cache buster in your templates with {{Config::get('cacheBuster')}} Just make sure that you add ‘cacheBuster’ to your production build!

Example
file.css?{{Config::get('cacheBuster')}}

If you like this and also use WordPress, Have a look at my solution for busing its cache over here.


Adam Patterson

Adam Patterson

User Interface Designer & Developer with a background in UX. I have spent 5 years as a professionally certified bicycle mechanic and ride year-round.

I am a husband and father of two, I enjoy photography, music, movies, coffee, and good food.

You can find me on Twitter, Instagram, and YouTube!