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

Assets Laravel Package

21torr/assets

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require 21torr/assets
    

    Ensure compatibility with your firefly version (see README requirements).

  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="21TORR\AssetsBundle\AssetsBundle" --tag=config
    

    Update config/assets.php with your storage paths (e.g., public, private).

  3. First Use Case Upload an asset via the Firefly UI (if integrated) or manually via:

    use 21TORR\AssetsBundle\Model\Asset;
    
    $asset = new Asset();
    $asset->setFile('path/to/file.jpg');
    $asset->save();
    

    Access the URL via:

    $asset->getUrl(); // e.g., `/assets/123/file.jpg`
    
  4. Key Directories

    • config/assets.php: Core settings (paths, CDN, etc.).
    • src/21TORR/AssetsBundle/: Core logic (models, services).
    • Resources/config/: Default configurations.

Implementation Patterns

Core Workflows

  1. Asset Uploads

    • Manual Uploads: Use the Asset model to handle files:
      $asset = new Asset();
      $asset->setFile($request->file('image'));
      $asset->setMimeType($request->file('image')->getMimeType());
      $asset->save();
      
    • Firefly Integration: Leverage Firefly’s UI for drag-and-drop uploads (if using Firefly 2.x+). Configure routes in routing.yml:
      assets_upload:
          path: /assets/upload
          defaults: { _controller: AssetsBundle:Asset:upload }
      
  2. Asset URLs and Paths

    • Generate URLs dynamically:
      $url = $this->get('assets')->generateUrl($asset);
      // or via Twig:
      {{ asset(asset.id) }}
      
    • Customize paths in config/assets.php:
      'paths' => [
          'public' => 'uploads/%year%/%month%/%day%',
      ],
      
  3. Asset Processing

    • Use Symfony’s Asset component for versioned URLs:
      $this->get('assets')->getUrl($asset, ['version' => '1.0']);
      
    • Integrate with Symfony’s AssetMapper for cache-busting:
      <img src="{{ asset_url(asset.id) }}">
      
  4. Batch Operations

    • Bulk uploads via CLI:
      php artisan assets:import path/to/directory
      
    • Query assets with Eloquent:
      $assets = Asset::where('mime_type', 'like', 'image/%')->get();
      

Integration Tips

  • Firefly Sync: If using Firefly, sync assets via its API or event listeners:
    // Example: Listen for Firefly entity events
    Firefly\Event\EventDispatcher::addListener(
        'firefly.entity.created',
        function ($entity) {
            // Auto-assign assets to entities
        }
    );
    
  • Custom Storage: Extend the AssetStorage service to support S3 or other backends:
    // config/services.yaml
    assets.storage:
        class: App\Service\CustomAssetStorage
        arguments: ['@assets.storage.adapter']
    

Gotchas and Tips

Pitfalls

  1. Archived Package

    • No active maintenance; use symfony/asset for new projects.
    • Fork or migrate if critical functionality is needed.
  2. Firefly Dependency

    • Without Firefly, some features (e.g., UI uploads) may not work. Use standalone Symfony asset handling instead.
    • Check composer.json for firefly version conflicts.
  3. Path Configuration

    • Incorrect paths.public in config/assets.php breaks URL generation.
    • Ensure directories are writable (e.g., storage/app/public/assets).
  4. Mime Type Handling

    • Manual uploads require explicit setMimeType(); rely on Symfony’s MimeTypeGuesser for auto-detection:
      use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
      $guesser = new MimeTypeGuesser();
      $asset->setMimeType($guesser->guess($file->getPathname()));
      
  5. Caching Issues

    • Clear cache after config changes:
      php artisan cache:clear
      
    • Use asset_version in Twig to bust caches:
      <img src="{{ path('assets_url', { id: asset.id, version: '1.0' }) }}">
      

Debugging

  • Missing Assets: Check storage/logs/laravel.log for file system errors. Verify paths.public exists and is writable.
  • 404 Errors: Ensure Asset model events (saving, saved) aren’t interfering with path generation.
  • Firefly Conflicts: Disable Firefly’s asset handling if using standalone:
    // config/firefly.php
    'assets' => false,
    

Extension Points

  1. Custom Asset Models Extend 21TORR\AssetsBundle\Model\Asset for domain-specific logic:

    namespace App\Model;
    
    use 21TORR\AssetsBundle\Model\Asset as BaseAsset;
    
    class ProductAsset extends BaseAsset
    {
        public function getProduct()
        {
            return $this->belongsTo(Product::class);
        }
    }
    
  2. Storage Adapters Override the default storage adapter (e.g., for S3):

    // src/Service/CustomStorageAdapter.php
    namespace App\Service;
    
    use 21TORR\AssetsBundle\Storage\AdapterInterface;
    
    class CustomStorageAdapter implements AdapterInterface
    {
        public function save($file, $path)
        {
            // Custom logic (e.g., S3 upload)
        }
    }
    

    Register in config/services.yaml:

    assets.storage.adapter: App\Service\CustomStorageAdapter
    
  3. Events Listen for asset events (e.g., asset.pre_save):

    // EventListener.php
    namespace App\Listener;
    
    use 21TORR\AssetsBundle\Event\AssetEvent;
    
    class AssetListener
    {
        public function onPreSave(AssetEvent $event)
        {
            $event->getAsset()->setUserId(auth()->id());
        }
    }
    

    Register in services.yaml:

    services:
        App\Listener\AssetListener:
            tags:
                - { name: kernel.event_listener, event: asset.pre_save, method: onPreSave }
    

Performance Tips

  • Disable Debug Mode: Set 'debug' => false in config/assets.php to disable cache-busting in production.
  • Use CDN: Configure cdn_url in config/assets.php for offloaded assets:
    'cdn' => [
        'enabled' => true,
        'url' => 'https://cdn.example.com/assets/%id%',
    ],
    
  • Batch Processing: Use Asset::chunk() for large datasets to avoid memory issues:
    Asset::chunk(100, function ($assets) {
        foreach ($assets as $asset) {
            // Process asset
        }
    });
    
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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope