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 Setup

  1. Installation:

    composer require van-ons/filament-attachment-library:^2.0
    php artisan filament-attachment-library:install
    

    Follow the CLI prompts to set up the custom Filament theme and register it in your panel provider.

  2. Configure Storage Disk (optional): Add to .env:

    ATTACHMENTS_DISK=s3  # or any other disk name
    
  3. Register the Plugin: In your PanelProvider:

    ->plugin(FilamentAttachmentLibrary::make()->navigationGroup('Files'))
    
  4. First Use Case: Add HasAttachments trait to your model:

    use VanOns\LaravelAttachmentLibrary\Concerns\HasAttachments;
    
    class Product extends Model {
        use HasAttachments;
    }
    

    Add the AttachmentField to your Filament resource form:

    AttachmentField::make('gallery')->relationship()->collection('product_images')
    

Implementation Patterns

Core Workflows

1. Single-Attachment Storage (Direct Column)

  • Use AttachmentField::make('field_name') for storing a single attachment in a model column.
  • Example:
    AttachmentField::make('featured_image')
        ->required()
        ->image()
        ->imagePreviewHeight('200px')
    

2. Multi-Attachment Storage (Relationship-Based)

  • Use AttachmentField::make('field_name')->relationship() for storing multiple attachments via the attachments relationship.
  • Customize the collection name:
    AttachmentField::make('gallery')->relationship()->collection('product_gallery')
    
  • Define a dedicated relationship method in your model:
    public function gallery(): MorphToMany {
        return $this->attachmentCollection('product_gallery');
    }
    

3. Frontend Display

  • Use the Blade component for images:
    <x-laravel-attachment-library-image :src="$product->gallery->first()" />
    
  • Customize Glide image processing (width/height, format, etc.) via glide.php:
    'default' => [
        'width' => 800,
        'height' => 600,
        'fit' => 'crop',
    ],
    

4. Plugin Configuration

  • Override default settings in config/attachment-library.php:
    'max_file_size' => '10MB', // Default: 5MB
    'allowed_mime_types' => ['image/*', 'application/pdf'],
    'disk' => env('ATTACHMENTS_DISK', 'public'),
    

5. Integration with Filament Resources

  • Display attachments in tables:
    use VanOns\FilamentAttachmentLibrary\Columns\AttachmentColumn;
    
    AttachmentColumn::make('gallery')
        ->collection('product_gallery')
        ->image()
        ->imagePreviewHeight('50px')
    
  • Bulk actions (e.g., delete all attachments for a record):
    public static function getBulkActions(): array {
        return [
            Actions\DeleteAllAttachments::make(),
        ];
    }
    

Gotchas and Tips

Pitfalls

  1. TailwindCSS Styling:

    • Forgetting to include the package’s Blade templates in tailwind.config.js:
      content: [
          './vendor/van-ons/filament-attachment-library/resources/**/*.blade.php',
      ]
      
    • Fix: Run php artisan make:filament-theme [PANEL_NAME] and update tailwind.config.js.
  2. Disk Conflicts:

    • Using a shared disk (e.g., public) for attachments can cause conflicts with other files.
    • Fix: Dedicate a disk (e.g., attachments) and set ATTACHMENTS_DISK in .env.
  3. Glide Configuration:

    • Glide processing may fail if the glide package is not installed or misconfigured.
    • Fix: Ensure spatie/laravel-medialibrary and intervention/image (or spatie/image-optimizer) are installed.
  4. Relationship Caching:

    • Eager-loading attachments can bloat queries. Use with() sparingly:
      Product::with(['gallery' => function($query) {
          $query->limit(3); // Limit attachments per model
      }])->get();
      
  5. File Validation:

    • Default MIME type checks may block legitimate files (e.g., image/jpeg vs. image/pjpeg).
    • Fix: Extend allowed_mime_types in config/attachment-library.php:
      'allowed_mime_types' => ['image/*', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
      

Debugging Tips

  1. Attachment Not Showing?

    • Check if the HasAttachments trait is applied to the model.
    • Verify the collection name matches between the field and relationship.
  2. Upload Fails Silently

    • Enable debug mode and check Laravel logs for Symfony\Component\HttpFoundation\File\UploadedFile errors.
    • Ensure the disk is writable:
      php artisan storage:link
      
  3. Glide Processing Errors

    • Clear Glide cache:
      php artisan glide:clear
      
    • Check glide.php for correct disk and path configurations.

Extension Points

  1. Custom Attachment Models:

    • Extend the Attachment model to add custom fields (e.g., alt_text, metadata):
      php artisan make:model AttachmentExtension --extend=VanOns\LaravelAttachmentLibrary\Models\Attachment
      
  2. Custom Storage Logic:

    • Override the AttachmentServiceProvider to change upload behavior:
      use VanOns\LaravelAttachmentLibrary\AttachmentServiceProvider as BaseProvider;
      
      class CustomAttachmentServiceProvider extends BaseProvider {
          public function register() {
              $this->app->singleton(\VanOns\LaravelAttachmentLibrary\Contracts\AttachmentUploader::class, function ($app) {
                  return new CustomUploader();
              });
          }
      }
      
  3. Custom UI Components:

    • Override the default AttachmentField or AttachmentColumn by publishing views:
      php artisan vendor:publish --tag=filament-attachment-library-views
      
    • Modify resources/views/vendor/filament-attachment-library/... to customize the UI.
  4. Event Listeners:

    • Listen for attachment events (e.g., AttachmentCreated, AttachmentDeleted) to trigger actions:
      use VanOns\LaravelAttachmentLibrary\Events\AttachmentCreated;
      
      event(new AttachmentCreated($attachment));
      
    • Register listeners in EventServiceProvider:
      protected $listen = [
          AttachmentCreated::class => [
              \App\Listeners\LogAttachmentCreation::class,
          ],
      ];
      
  5. Bulk Operations:

    • Add custom bulk actions to the plugin:
      use VanOns\FilamentAttachmentLibrary\Actions\BulkAction;
      
      BulkAction::make('compress-images')
          ->action(function (array $records) {
              foreach ($records as $record) {
                  $record->gallery()->update(['width' => 800, 'height' => 600]);
              }
          }),
      
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope