Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Asset Helper Laravel Package

spatie/asset-helper

Laravel 4 helper to generate URLs for revisioned/cache-busted assets. Given an original name like admin.css, it finds the hashed version in your public assets folder and returns a URL such as /assets/admin.0ce5cb43.css.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/asset-helper
    

    Add the service provider to config/app.php under providers:

    Spatie\AssetHelper\AssetHelperServiceProvider::class,
    
  2. Publish Config (Optional):

    php artisan vendor:publish --provider="Spatie\AssetHelper\AssetHelperServiceProvider"
    

    This generates a config file at config/asset-helper.php (default settings are fine for most cases).

  3. First Use Case: In a Blade template or PHP file, retrieve a revisioned asset URL:

    use Spatie\AssetHelper\Facades\Asset;
    
    // Blade
    <link href="{{ Asset::getUrl('css/admin.css') }}" rel="stylesheet">
    
    // PHP
    $assetUrl = Asset::getUrl('css/admin.css');
    

Where to Look First

  • Facade: Spatie\AssetHelper\Facades\Asset (primary entry point).
  • Config: config/asset-helper.php (customize asset paths, hash length, or storage).
  • Service Provider: Spatie\AssetHelper\AssetHelperServiceProvider (for advanced customization).

Implementation Patterns

Core Workflows

  1. Basic Asset URL Generation:

    // Returns `/assets/css/admin.abc123.css` (assuming default config)
    Asset::getUrl('css/admin.css');
    
  2. Dynamic Asset Paths: Use the getUrl() method with relative paths (e.g., 'images/logo.png'). The package resolves paths relative to the asset_path config value (default: public/assets).

  3. Blade Directives: Register a custom Blade directive for convenience (add to AppServiceProvider):

    Blade::directive('asset', function ($expression) {
        return "<?php echo Spatie\\AssetHelper\\Facades\\Asset::getUrl($expression); ?>";
    });
    

    Usage in Blade:

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    
  4. Asset Versioning in JavaScript:

    // Dynamically fetch asset URLs in JS
    const cssUrl = "{{ Asset::getUrl('css/app.css') }}";
    
  5. Integration with Laravel Mix:

    • Ensure Mix outputs files to the asset_path (e.g., public/assets).
    • Use mix.version() to generate hashes, but let asset-helper handle URL generation:
      // In a Blade template
      <script src="{{ Asset::getUrl(mix('js/app.js')) }}"></script>
      
  6. Conditional Asset Loading:

    @if (Auth::check())
        <link href="{{ Asset::getUrl('css/dashboard.css') }}" rel="stylesheet">
    @endif
    

Advanced Patterns

  1. Custom Hashing Logic: Override the default hash generation by binding a custom AssetHelper instance:

    $this->app->bind('asset.helper', function () {
        return new CustomAssetHelper();
    });
    

    Implement Spatie\AssetHelper\AssetHelperInterface.

  2. Asset Groups: Define multiple asset paths in config (e.g., cdn_assets, local_assets) and switch dynamically:

    Asset::setPath('cdn_assets');
    Asset::getUrl('js/vendor.js'); // Uses CDN path
    
  3. Asset Existence Checks: Combine with Storage::exists() to verify assets before linking:

    if (Storage::disk('public')->exists("assets/css/{$filename}.css")) {
        echo Asset::getUrl("css/{$filename}.css");
    }
    

Gotchas and Tips

Pitfalls

  1. Path Resolution:

    • Issue: Asset::getUrl('css/admin.css') returns /assets/css/admin.css (note the double css).
    • Fix: Use Asset::getUrl('admin.css') if asset_path is public/assets. Double-check asset_path in config.
  2. Hash Mismatches:

    • Issue: Asset URLs don’t update after file changes if the hash isn’t regenerated.
    • Fix: Ensure your build process (e.g., Laravel Mix) includes mix.version() or manually append hashes:
      // In a custom helper
      function assetWithHash($path) {
          return Asset::getUrl($path);
      }
      
  3. Case Sensitivity:

    • Issue: Linux servers may treat Admin.css vs admin.css as different files.
    • Fix: Normalize filenames in config or pre-process paths:
      Asset::setPath(strtolower(Asset::getPath()));
      
  4. Caching Headaches:

    • Issue: Old asset URLs linger in browser cache due to incorrect hashing.
    • Fix: Use a longer hash length in config (hash_length = 16) or implement cache-busting queries:
      Asset::getUrl('js/app.js?v=' . filemtime(public_path('assets/js/app.js')));
      
  5. Dependents:

    • Issue: The package has no dependents, so community integrations (e.g., with Vite or Inertia.js) are untested.
    • Fix: Test thoroughly if combining with modern asset pipelines.

Debugging Tips

  1. Log Asset Paths:

    dd(Asset::getPath(), Asset::getUrl('css/test.css'));
    

    Verify the resolved path matches your public folder structure.

  2. Disable Hashing (Temporarily): Override the shouldHash() method in a custom AssetHelper to debug:

    public function shouldHash($path) {
        return false; // Disable hashing for testing
    }
    
  3. Check File Permissions: Ensure the asset_path directory is writable by the web server:

    chmod -R 755 public/assets
    

Extension Points

  1. Custom Hash Algorithms: Extend Spatie\AssetHelper\AssetHelper to use SHA-256 or other hashes:

    public function getHash($filename) {
        return hash_file('sha256', public_path("assets/{$filename}"));
    }
    
  2. Asset Metadata: Store additional metadata (e.g., last-modified timestamps) in the hash:

    public function getHash($filename) {
        $path = public_path("assets/{$filename}");
        return hash('md5', filemtime($path) . file_get_contents($path));
    }
    
  3. Fallback URLs: Provide fallback URLs if the asset is missing:

    public function getUrl($path) {
        $url = parent::getUrl($path);
        return Storage::disk('public')->exists($url) ? $url : 'fallback.css';
    }
    
  4. Environment-Specific Paths: Dynamically set paths based on the environment:

    Asset::setPath(config("asset-helper.{$this->app->environment()}_path"));
    

Config Quirks

  • asset_path: Defaults to public/assets. Trailing slashes are required (e.g., public/assets/).
  • hash_length: Defaults to 8. Longer hashes reduce collision risk but increase URL length.
  • hash_algorithm: Defaults to md5. Override in config or via custom AssetHelper.

Performance Notes

  • Avoid Regenerating Hashes: Cache hashes in a database or file if assets rarely change.
  • Lazy Loading: Defer asset URL generation until runtime to avoid early file system checks:
    // In a controller
    $assetUrls = collect(['css/app.css', 'js/app.js'])
        ->map(fn($path) => Asset::getUrl($path));
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport