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

Filament Attachment Library Laravel Package

van-ons/filament-attachment-library

Filament Attachment Library adds a simple attachments manager to your Filament panel: upload files, browse and select existing attachments, and store them in a central library. Includes installer command, migrations/assets, and Tailwind-ready templates.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the package:

    composer require van-ons/filament-attachment-library:^2.0
    php artisan filament-attachment-library:install
    
  2. Set up a custom Filament theme (required for Tailwind styling):

    php artisan make:filament-theme [PANEL_NAME]
    

    Add this to resources/css/filament/[PANEL_NAME]/theme.css:

    @source '../../../../vendor/van-ons/filament-attachment-library/resources/**/*.blade.php'
    
  3. Register the plugin in your PanelProvider:

    use VanOns\FilamentAttachmentLibrary\FilamentAttachmentLibrary;
    
    public function panel(Panel $panel): Panel {
        return $panel
            ->plugin(FilamentAttachmentLibrary::make()->navigationGroup('Files'));
    }
    
  4. Use the AttachmentField in a Filament resource:

    use VanOns\FilamentAttachmentLibrary\Forms\Components\AttachmentField;
    
    public static function form(Form $form): Form {
        return $form->schema([
            AttachmentField::make('featured_image'), // Stores in a column
            AttachmentField::make('gallery')->relationship(), // Uses `HasAttachments` trait
        ]);
    }
    
  5. Display attachments in Blade:

    <x-laravel-attachment-library-image :src="$attachment" />
    

First Use Case: Adding a Gallery to a Product

  1. Add the HasAttachments trait to your Product model:
    use VanOns\LaravelAttachmentLibrary\Concerns\HasAttachments;
    
    class Product extends Model {
        use HasAttachments;
    }
    
  2. Add the AttachmentField to your Filament resource form:
    AttachmentField::make('gallery')->relationship()->collection('product_gallery')
    
  3. Display the gallery in a view:
    @foreach($product->gallery as $image)
        <x-laravel-attachment-library-image :src="$image" />
    @endforeach
    

Implementation Patterns

Core Workflows

1. Storing Attachments in a Column

  • Use AttachmentField::make('column_name') for direct storage in a model column (e.g., featured_image).
  • Ideal for single-file attachments (e.g., profile pictures, banners).
  • Example:
    AttachmentField::make('logo')
        ->image()
        ->required()
        ->maxFiles(1);
    

2. Storing Attachments via Relationship

  • Use AttachmentField::make('field_name')->relationship() for dynamic collections (e.g., galleries, documents).
  • Requires the HasAttachments trait on the model.
  • Example:
    AttachmentField::make('documents')
        ->relationship()
        ->collection('contracts')
        ->mime('application/pdf');
    

3. Tenant-Specific Storage

  • Dynamically set base paths for multi-tenant apps:
    FilamentAttachmentLibrary::make()
        ->basePath(fn () => 'tenants/' . Filament::getTenant()?->slug)
    

4. Validation Patterns

  • MIME Types:
    AttachmentField::make('avatar')->mime('image/jpeg,image/png');
    
  • File Types:
    AttachmentField::make('video')->video();
    AttachmentField::make('document')->text();
    
  • Quantity:
    AttachmentField::make('gallery')->multiple()->minFiles(1)->maxFiles(10);
    

Integration Tips

With Eloquent Models

  • Add a custom relationship method for cleaner usage:
    public function gallery(): MorphToMany {
        return $this->attachmentCollection('gallery');
    }
    
  • Eager-load attachments in queries:
    Product::with('gallery')->get();
    

With Filament Resources

  • Table Columns: Display attachments in tables using AttachmentColumn:
    use VanOns\FilamentAttachmentLibrary\Tables\Columns\AttachmentColumn;
    
    Tables\Columns\AttachmentColumn::make('featured_image')
        ->image()
        ->width(50)
        ->height(50);
    
  • Widgets: Show attachment stats in dashboards:
    use VanOns\FilamentAttachmentLibrary\Widgets\AttachmentStats;
    
    public static function widgets(): array {
        return [
            AttachmentStats::make(),
        ];
    }
    

Frontend Display

  • Blade Components:
    <!-- Single image -->
    <x-laravel-attachment-library-image :src="$product->featured_image" />
    
    <!-- Thumbnail -->
    <x-laravel-attachment-library-image :src="$image" width="100" height="100" />
    
  • Glide Integration: Leverage Glide for image manipulation:
    <x-laravel-attachment-library-image :src="$image" width="300" height="200" />
    

Customization

  • Override Views: Publish and modify Blade templates:
    php artisan vendor:publish --tag="filament-attachment-library-views"
    
  • Extend JavaScript: Modify Alpine components in resources/js/plugin.js and rebuild:
    npm run build
    

Gotchas and Tips

Pitfalls

  1. Tailwind Styling Requirement:

    • Issue: Missing styles if the custom theme isn’t properly registered.
    • Fix: Ensure theme.css includes @source and the theme is registered in PanelProvider:
      ->theme('custom-theme')
      
  2. Disk Conflicts:

    • Issue: Using the default public disk may cause conflicts with other files.
    • Fix: Dedicate a disk (e.g., attachments) in filesystems.php and set it in .env:
      ATTACHMENTS_DISK=attachments
      
  3. Base Path Overrides:

    • Issue: Dynamic paths (e.g., tenant-specific) may not update on existing attachments.
    • Fix: Use a migration to move old files or implement a fallback path.
  4. Relationship Caching:

    • Issue: Attachments not appearing in relationships after updates.
    • Fix: Clear the model’s event dispatcher or use refresh():
      $product->load('gallery');
      
  5. Glide Configuration:

    • Issue: Images not resizing or failing to load.
    • Fix: Verify glide.php is configured and the disk is accessible:
      'driver' => 'public',
      'source' => storage_path('app/public'),
      

Debugging Tips

  1. Log Attachment Paths:

    • Temporarily log paths in AttachmentService to verify storage:
      \Log::debug('Attachment path:', [$attachment->path]);
      
  2. Check Disk Permissions:

    • Ensure the disk’s storage directory is writable:
      chmod -R 755 storage/app/attachments
      
  3. Validate MIME Types:

    • Use dd($request->file()->getMimeType()) to debug uploads.
  4. Clear Filament Cache:

    • After updates, run:
      php artisan filament:clear-cache
      

Extension Points

  1. Custom Storage Engines:

    • Extend VanOns\LaravelAttachmentLibrary\Contracts\AttachmentStorage to support S3, Dropbox, etc.
  2. Event Listeners:

    • Listen for attachment.created, attachment.deleted, etc., to trigger actions:
      use VanOns\LaravelAttachmentLibrary\Events\AttachmentCreated;
      
      event(new AttachmentCreated($attachment));
      
  3. Custom Fields:

    • Extend AttachmentField to add features like:
      • Drag-and-drop ordering.
      • Bulk actions (e.g., delete multiple).
  4. Widget Customization:

    • Override AttachmentStats to display custom metrics (e.g., "Total Storage Used").

Configuration Quirks

  1. attachment-library.php:

    • Override defaults like max_file_size (in MB) or allowed_mime_types.
    • Example:
      'max_file_size' => 10, // 10MB
      'allowed_mime_types' => ['image/*', 'application/pdf'],
      
  2. Glide Integration:

    • Disable Glide for performance if not needed:
      'glide' => [
          'enabled' => false,
      ]
      
  3. Navigation Group:

    • Customize the plugin’s navigation label:
      FilamentAttachmentLibrary::make()->navigationLabel('Media Library')
      
  4. Asset Publishing:

    • After updating the package,
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity