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 Laravel Package

symfony/asset

Symfony Asset Component generates URLs for web assets (CSS, JS, images) with built-in versioning for cache busting. Supports base paths, packages, and CDNs to keep asset links consistent across environments and deployments.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel-Native Complement: The symfony/asset package excels at server-side asset URL generation and versioning, addressing gaps in Laravel’s built-in asset() helper (e.g., no native fingerprinting or CDN support). It integrates seamlessly with Laravel’s service container, Blade templates, and asset pipelines (e.g., Laravel Mix/Vite).
  • Modular Design: The component’s Packages interface allows for flexible configuration (e.g., PathPackage, JsonManifestPackage for Mix/Vite compatibility). This enables granular adoption—e.g., using it only for non-bundled assets while preserving Laravel’s native helpers for others.
  • Performance-Cache Synergy: Supports cache-busting via fingerprinting (e.g., app.abc123.css) and environment-aware versioning (e.g., disabling hashes in dev). Critical for high-traffic apps or asset-heavy SPAs/MPAs.
  • Symfony Ecosystem: Leverages Symfony’s dependency injection and PSR standards, reducing friction in Laravel applications that already use Symfony components (e.g., HTTP Client, UX).

Integration Feasibility

  • Minimal Boilerplate: Integration requires ~5–10 lines of code (e.g., service provider registration or middleware). Example:
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(\Symfony\Component\Asset\Packages::class, fn() =>
            new \Symfony\Component\Asset\PathPackage(public_path(), true) // Enable versioning
        );
    }
    
  • Blade Template Integration: Replace {{ asset('...') }} with:
    @inject('assets', 'Symfony\Component\Asset\Packages')
    <link href="{{ $assets->getUrl('css/app.css') }}" rel="stylesheet">
    
  • Laravel Mix/Vite Compatibility: Use JsonManifestPackage to defer to Mix/Vite’s manifest:
    $package = new \Symfony\Component\Asset\JsonManifestPackage(
        public_path('mix-manifest.json'),
        'https://cdn.example.com'
    );
    
  • Middleware for Global Rewrites: Override asset URLs application-wide via Laravel middleware:
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->setContent(
            preg_replace(
                '/href="(\/assets\/[^"]+)"/',
                'href="' . $this->assets->getUrl('$1') . '"',
                $response->getContent()
            )
        );
        return $response;
    }
    

Technical Risk

  • Versioning Collisions: If both Laravel Mix and symfony/asset generate hashes for the same files, cache inconsistencies may arise. Mitigation:
    • Option 1: Use symfony/asset only for non-Mix assets (e.g., raw public/ files).
    • Option 2: Configure JsonManifestPackage to respect Mix’s hashes:
      $package = new JsonManifestPackage(
          public_path('mix-manifest.json'),
          null, // No base URL (use Mix’s hashes)
          true  // Strict mode
      );
      
  • PHP Version Requirements: Symfony 8.x requires PHP 8.4+, while Laravel 10 supports PHP 8.1+. Risk: Downgrade to Symfony 7.x (PHP 8.1+) if needed.
  • CDN/Subdomain Complexity: While the package supports base_urls, signed URLs or dynamic subdomains may require custom logic (e.g., middleware to rewrite URLs at runtime).
  • Legacy Asset Paths: Hardcoded paths in templates (e.g., <img src="/img/logo.png">) will break if not migrated to dynamic generation. Use regex search/replace or static analysis tools (e.g., PHPStan) to audit templates.

Key Questions

  1. Adoption Scope:
    • Will this replace all asset URLs (e.g., asset(), mix()), or only specific cases (e.g., raw public/ files)?
    • Are there third-party packages (e.g., Spatie Media Library) that generate asset URLs and could conflict?
  2. Versioning Strategy:
    • Should fingerprinting be enabled by default (prod) or opt-in (dev)?
    • How will cache invalidation work if Mix and symfony/asset both generate hashes?
  3. Performance Impact:
    • Will dynamic versioning add measurable overhead? Test with:
      • Asset-heavy pages (e.g., 50+ CSS/JS files).
      • Cold vs. warm starts (cached Packages instance).
  4. Team Workflow:
    • Will developers need to update Blade templates (e.g., @inject directives)?
    • Are there CI/CD pipelines that rely on static asset paths (e.g., for previews)?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Native compatibility with:
    • Service Container: Register Packages as a singleton or context-bound instance.
    • Blade Templates: Use @inject or service binding for dynamic asset URLs.
    • Middleware: Globally rewrite asset paths (e.g., for CDN support).
    • Asset Pipelines: Integrate with Laravel Mix/Vite via JsonManifestPackage.
  • PHP Version Alignment:
    • Symfony 8.x: Requires PHP 8.4+ (Laravel 11+).
    • Symfony 7.x: Supports PHP 8.1+ (Laravel 10).
    • Recommendation: Use Symfony 7.4.x for broader Laravel compatibility.
  • Tooling Compatibility:
    • Laravel Mix/Vite: Leverage mix-manifest.json via JsonManifestPackage.
    • CDNs: Configure base_urls for asset delivery (e.g., https://cdn.example.com).
    • Storage Systems: Works with local public/, S3, or custom paths.

Migration Path

Phase Action Tools/Examples
Assessment Audit asset usage: Identify hardcoded paths, Mix/Vite dependencies. grep -r "href=\"/assets/" app/ or PHPStan rules.
Pilot Integration Replace non-Mix assets (e.g., raw public/ files) with PathPackage. new PathPackage(public_path(), true) in a service provider.
Blade Migration Update templates to use @inject or service binding. @inject('assets', 'Symfony\Component\Asset\Packages')
Mix/Vite Sync Configure JsonManifestPackage for bundled assets. new JsonManifestPackage(public_path('mix-manifest.json'))
Global Rewrite Add middleware for legacy asset paths (optional). Regex-based URL rewriting middleware.
Testing Validate cache-busting, CDN delivery, and dev/prod behavior. Load tests, cache headers inspection (e.g., curl -I).
Rollout Deploy in stages (e.g., non-critical routes first). Feature flags or environment-based toggles.

Compatibility

  • Laravel Versions:
    • Laravel 10.x: Use Symfony 7.x (PHP 8.1+).
    • Laravel 11.x: Use Symfony 8.x (PHP 8.4+).
  • Asset Tools:
    • Laravel Mix/Vite: Full support via JsonManifestPackage.
    • Encore: Limited support (requires manual manifest path configuration).
    • Custom Build Tools: Use PathPackage for raw asset directories.
  • Caching Layers:
    • Varnish/Nginx: Cache-busting headers (e.g., Cache-Control: max-age=31536000, immutable) work with fingerprinting.
    • CDNs: Test with signed URLs or custom origin configurations.

Sequencing

  1. Phase 1: Non-Critical Assets
    • Migrate static assets (e.g., public/img/, public/css/) using PathPackage.
    • Risk: Low (isolated to non-bundled files).
  2. Phase 2: Bundled Assets (Mix/Vite)
    • Integrate JsonManifestPackage for fingerprinted assets.
    • Risk: Medium (requires Mix manifest validation).
  3. Phase 3: Global Rewrites (Optional)

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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui