Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

brentxscholl's avatar

Auto generate a version for css file in <head>

I was having an issue with browsers not loading new css styles after updating my css file (due to browser cache). I solved this by adding a version to css link. However, this is a bit annoying because every time I want to deploy changes to my server I have to update the css version so the user's browser loads the new changes.

Here is what I'm currently doing in the <head>:

<link href="{{ asset('css/main.css') }}?v=13" media="all" rel="stylesheet" type="text/css"/>

Every time I deploy new css I have to update the version to v=14 then v=15 then v=16 etc. so that it is always unique in my users browser.

Is there a way I can auto generate a version here? I was thinking maybe grabbing the date the file was updated and adding that as the version. that way it will always be unique, but I'm not sure how this can be done in Laravel blade.

How do you guys handle file caching and versions?

Thanks!

0 likes
8 replies
MohammedSB's avatar

@brentxscholl You can use "?ver=3.0.1" after any file in your head or footer section.

For example

  • Script tag <script src="{{ asset('YOUR PATH/YOUR SCRIPT.js?ver=0.0.2') }}"></script>

  • Style tag <link src="{{ asset('YOUR PATH/YOUR ASSET.css?ver=0.0.2') }}">

Snapey's avatar

@MohammedSB But then you have to remember to manually change the version each time....

MohammedSB's avatar

@Snapey yes correct, also there is another method but I don't prefer to use it.

  • First create helper class
function assetVersion()
{
	return '0.0.2';
}

and in your base layout use the following,

<link src="{{ asset('YOUR PATH/YOUR ASSET.css?ver=' . assetVersion()) }}">

with this solution, you will need to update the version in one place each time you want to update it. but i don't thing it's the best way for the performance

1 like
jillii's avatar

When you enqueue your styles, append the path with the date that the file was last modified. You can get that dynamically using filemtime()

wp_enqueue_style('sage/main.css', asset_path('styles/main.css') . '?ver=' . filemtime(get_stylesheet_directory() . '/../dist/styles/main.css'), false, null);

If you're calling your stylesheet straight in your html, I believe the equivalent would be

<link rel='stylesheet' id='sage/non-member-main.css-css' href='path/to/stylesheet ?ver=<?php echo filemtime(path/to/stylesheet) ?>' />

Please or to participate in this conversation.