My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Laravel asset versioning (Cache busting)

Laravel asset versioning (Cache busting)

Emil Moe's photo
Emil Moe
·Mar 15, 2017

Background

We all faced the issue. New modifications are made to the javascript or stylesheet and you are eager to inform the client, that the page was updated according to their requests. However everytime you struggle because you have to teach your clients how to clear cache and cross fingers that their customers do so as well.

This is where asset versioning come in handy.

What asset versioning does is every time you compile it will compile a new filename for your css and js files and by dedicated functions in Laravel keep track of the new filename. In other words it's a new unique file and your cache nightmares are past.

How to set it up

First of for your reference, you should be aware of the documentation laravel.com/docs/5.4/mix. However I will here demonstrate how it's done in a few easy steps and you will no longer have to worry about it. You will continue to compile your assets as usual.

You probably already enclose your assets with the asset() function. For example:

<link href="{{ asset('css/app.css') }}" rel="stylesheet">
[...]
<script src="{{ asset('js/app.js') }}"></script>

You need to replace this function with 2 other functions url() and elixir() (from Laravel 5.4 called mix())

<link href="{{ url(elixir('css/app.css')) }}" rel="stylesheet">
[...]
<script src="{{ url(elixir('js/app.js')) }}"></script>

Or from Laravel 5.4

<link href="{{ url(mix('css/app.css')) }}" rel="stylesheet">
[...]
<script src="{{ url(mix('js/app.js')) }}"></script>

Note that the path you define is the same as you would when you just used asset().

In your gulpfile.js you should wrap your assets into a version() function. I have here added the code around too, so it's easier for you to see how it should look.

elixir((mix) => {
    mix.sass('app.scss')
       .webpack('app.js')
    .version([
        'css/app.css',
        'js/app.js'
    ])
});

From Laravel 5.4 the procedure is a little different. Please have a look in the documentation for further information: laravel.com/docs/5.4/mix#versioning-and-cac..