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 helps generate and version URLs for web assets like CSS, JavaScript, and images. Supports cache busting via version strategies and base paths/URLs, making it easy to reference assets consistently across environments and CDNs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps for Laravel Developers

  1. Skip Installation: Do not install symfony/asset in a Laravel project. Laravel’s native tools (asset(), Vite, Mix) already handle asset management efficiently.
  2. First Use Case: Replace any manual asset URL generation (e.g., href="/css/app.css") with Laravel’s asset() helper:
    // Blade template
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    
    // PHP
    echo asset('js/app.js');
    
  3. For Vite Users: Use @vite() Blade directives for compiled assets:
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    
  4. Cache Busting: Rely on Vite’s or Mix’s automatic hashing (e.g., app.css?id=abc123). No manual versioning required.

Where to Look First


Implementation Patterns

Laravel-Native Workflows

1. Basic Asset URL Generation

Use Laravel’s asset() helper for all static file references:

// routes/web.php
Route::get('/styles', function () {
    return asset('css/styles.css'); // Returns full URL (e.g., /storage/css/styles.css)
});

Blade Example:

<img src="{{ asset('images/logo.png') }}" alt="Logo">

2. Vite Asset Compilation

Replace Mix with Vite for modern asset pipelines:

npm install vite @vitejs/plugin-laravel

Vite Config (vite.config.js):

import laravel from 'laravel-vite-plugin';
import { defineConfig } from 'vite';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
});

Blade Integration:

@vite(['resources/css/app.css', 'resources/js/app.js'])

3. Dynamic Asset Paths

Use Laravel’s mix() helper (if using Mix) or Vite’s dynamic imports:

<!-- Mix (deprecated but still used in some projects) -->
<script src="{{ mix('js/app.js') }}"></script>

<!-- Vite -->
<script type="module" src="{{ vite('resources/js/app.js') }}"></script>

4. Environment-Specific Assets

Leverage Laravel’s config('app.asset_path') or environment variables:

// config/app.php
'asset_path' => env('ASSET_PATH', 'storage'),

// In Blade
<link href="{{ config('app.asset_path') }}/css/app.css" rel="stylesheet">

5. CDN Integration

Use Laravel’s asset() with a CDN URL or environment-specific base paths:

// config/app.php
'asset_url' => env('ASSET_URL', null),

// Helper function (add to `app/Helpers.php`)
function cdn_asset($path) {
    return config('app.asset_url') ? config('app.asset_url') . $path : asset($path);
}

Usage:

<script src="{{ cdn_asset('js/vendor.js') }}"></script>

Symfony Integration (Hybrid Projects Only)

If you must use symfony/asset in a Laravel project (e.g., legacy Symfony module), follow these steps:

1. Installation

composer require symfony/asset

Note: Expect dependency conflicts with Laravel’s illuminate packages. Use replace in composer.json to avoid pulling in Symfony’s full stack:

"replace": {
    "symfony/http-foundation": "*",
    "symfony/options-resolver": "*"
}

2. Service Provider Setup

Register the AssetMapper in Laravel’s service container:

// app/Providers/AppServiceProvider.php
use Symfony\Component\Asset\Packages;
use Symfony\Component\Asset\PathPackage;
use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy;

public function register()
{
    $this->app->singleton('asset.mapper', function () {
        $packages = new Packages();
        $packages->addPackage(new PathPackage());

        return new \Symfony\Component\Asset\AssetMapper(
            $packages,
            new EmptyVersionStrategy()
        );
    });
}

3. Helper Function

Create a facade or helper to bridge Symfony’s AssetMapper with Laravel:

// app/Helpers/SymfonyAsset.php
use Symfony\Component\Asset\AssetMapper;

function symfony_asset(string $path): string
{
    return app(AssetMapper::class)->getUrl($path);
}

Usage:

<link href="{{ symfony_asset('css/symfony-module.css') }}" rel="stylesheet">

3. Versioning Strategies

For cache busting, configure a VersionStrategy (e.g., JsonManifestVersionStrategy for Vite/Mix manifests):

// In AppServiceProvider
use Symfony\Component\Asset\VersionStrategy\JsonManifestVersionStrategy;

$this->app->singleton('asset.version_strategy', function () {
    return new JsonManifestVersionStrategy(
        public_path('build/release-manifest.json') // Path to Vite/Mix manifest
    );
});

4. Blade Directive

Extend Blade to support Symfony’s asset syntax:

// app/Providers/BladeServiceProvider.php
use Illuminate\Support\Facades\Blade;

Blade::directive('symfonyAsset', function ($path) {
    return "<?php echo symfony_asset({$path}); ?>";
});

Usage:

<script src="{{ symfonyAsset('js/symfony-bundle.js') }}"></script>

Gotchas and Tips

Laravel-Specific Pitfalls

  1. Dependency Conflicts

    • Issue: Symfony’s symfony/http-foundation conflicts with Laravel’s illuminate/http.
    • Fix: Use composer why-not symfony/http-foundation to identify conflicts. Isolate Symfony dependencies in a separate module or use replace in composer.json.
  2. PHP Version Mismatch

    • Issue: symfony/asset v8+ requires PHP ≥8.4, but Laravel 11 targets PHP 8.2–8.3.
    • Fix: Pin to Symfony v7.x if using PHP <8.4, but expect limited feature support.
  3. Routing Conflicts

    • Issue: Symfony’s AssetMapper may generate URLs that conflict with Laravel’s routing (e.g., missing trailing slashes).
    • Fix: Extend PathPackage to normalize paths:
      use Symfony\Component\Asset\PathPackage;
      
      $packages->addPackage(new class extends PathPackage {
          public function getUrl($path): string
          {
              return parent::getUrl($path) . (str_ends_with($path, '/') ? '' : '/');
          }
      });
      
  4. Manifest File Paths

    • Issue: JsonManifestVersionStrategy expects a Symfony-style manifest (e.g., public/build/release.json), but Laravel’s Vite/Mix outputs mix-manifest.json or asset-manifest.json.
    • Fix: Create a custom strategy or preprocess the manifest:
      use Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface;
      
      class LaravelManifestVersionStrategy implements VersionStrategyInterface
      {
          public function getVersion(string $path): string
          {
              $manifest = json_decode(file_get_contents(public_path('build/asset-manifest.json')), true);
              return $manifest[$path] ?? '';
          }
      }
      
  5. Blade vs. Twig

    • Issue: Symfony’s asset functions (e.g., asset() in Twig) won’t work in Blade.
    • Fix: Use Laravel’s asset() or create a Blade directive (as shown above).
  6. Cache Invalidation

    • Issue: Mixing Symfony’s versioning with Laravel’s cache (e.g., php artisan cache:clear) may break asset URLs.
    • Fix: Ensure version strategies read from disk (not cache) or clear the cache
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