Easier caching with cached_asset()

Submitted by stidges - 10 years ago

This function will allow you to forget about cache busting mechanisms. It will use your desired method of cache busting, either <filename>.<buster>.<extension> (default) or <filename>.<extension>?<buster>. You can use this to replace asset() entirely and never worry about updating those pesky cache busters whenever you update a file!

if ( ! function_exists('cached_asset'))
{
    function cached_asset($path, $bustQuery = false)
    {
        // Get the full path to the asset.
        $realPath = public_path($path);

        if ( ! file_exists($realPath)) {
            throw new LogicException("File not found at [{$realPath}]");
        }

        // Get the last updated timestamp of the file.
        $timestamp = filemtime($realPath);

        if ( ! $bustQuery) {
            // Get the extension of the file.
            $extension = pathinfo($realPath, PATHINFO_EXTENSION);

            // Strip the extension off of the path.
            $stripped = substr($path, 0, -(strlen($extension) + 1));

            // Put the timestamp between the filename and the extension.
            $path = implode('.', array($stripped, $timestamp, $extension));
        } else {
            // Append the timestamp to the path as a query string.
            $path  .= '?' . $timestamp;
        }

        return asset($path);
    }
}

// Example usage:
<img src="{{ cached_asset('path/to/img.png') }}">
// Outputs: /path/to/img.1398483860.png

<link rel="stylesheet" href="{{ cached_asset('path/to/stylesheet.css', true) }}">
// Outputs: /path/to/stylesheet.css?1398483860