How to cache-bust assets on Laravel Forge
May 8, 2022
When hosting on Laravel Forge, you might find that your CSS or JavaScript assets are cached by your usersâ web browsers and donât update when you redeploy.
The solution is to âcache-bustâ your assets by giving each new deploy a unique version ID. So on every deploy, Laravel will change the URL of the assets, so that the cache expires.
For example, with versioning, your HTML will look like this:
<link rel="stylesheet" href="/css/app.css?id=8b6f7790f026272ce6ffa9573e030ce4">
To version your assets with Laravel Mix, add this to the end of your webpack.mix.js
file:
if (mix.inProduction()) {
mix.version();
}
This turns on versioning, but only if weâre running in production (not when youâre locally developing).
Next, youâll import assets using the mix()
helper instead of the asset()
helper. So replace things like this:
<!-- previously, you may have had this: -->
<script src="{{ asset('js/app.js') }}" defer></script>
with this:
<!-- replace it with this: -->
<script src="{{ mix('js/app.js') }}" defer></script>
That mix()
helper knows how to correctly add the random part to the end of the URL, in order to cache-busts your assets.
Subscribe to my newsletter!
A weekly round-up of new blog posts and updates to projects Iâm working on.