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

Laravel Attachment Library Laravel Package

van-ons/laravel-attachment-library

Attach files to Laravel Eloquent models with a simple HasAttachments trait and Attachment model. Includes installer command for migrations/assets and an attachments relationship to link existing uploads to any model.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require van-ons/laravel-attachment-library
    php artisan attachment-library:install
    

    This publishes migrations, config, and assets.

  2. Configure Disk (optional): Set ATTACHMENTS_DISK in .env to override the default public disk.

  3. Enable Attachments on Model: Add the HasAttachments trait to your Eloquent model:

    use VanOns\LaravelAttachmentLibrary\Concerns\HasAttachments;
    
    class Post extends Model {
        use HasAttachments;
    }
    
  4. First Use Case: Upload and attach a file:

    $attachment = \VanOns\LaravelAttachmentLibrary\Facades\AttachmentManager::upload($request->file('document'));
    $post->attachments()->attach($attachment);
    $post->save();
    

Implementation Patterns

Core Workflows

  1. Uploading Files:

    $attachment = AttachmentManager::upload($request->file('file'), [
        'directory' => 'posts/' . $post->id,
        'metadata' => ['user_id' => auth()->id()]
    ]);
    
  2. Managing Attachments via Model:

    // Attach existing attachment
    $post->attachments()->attach($attachmentId);
    
    // Detach attachment
    $post->attachments()->detach($attachmentId);
    
    // Sync attachments (replace all)
    $post->attachments()->sync([$attachmentId1, $attachmentId2]);
    
  3. Directory Management:

    // Create directory for a model
    $dir = AttachmentManager::createDirectory('posts/' . $post->id);
    
    // Move attachment to directory
    AttachmentManager::move($attachment, 'posts/' . $post->id);
    
  4. Responsive Images:

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

    Or programmatically:

    $resized = Resizer::src($attachment)->width(300)->height(200)->resize();
    

Integration Tips

  • Form Requests: Validate file uploads using Laravel’s built-in validation:
    $request->validate([
        'file' => 'required|file|max:10240', // 10MB
    ]);
    
  • Filament Integration: Use the companion package filament-attachment-library for admin panel support.
  • Events: Listen for attachment events (e.g., AttachmentCreated) to trigger notifications or logs:
    event(new AttachmentCreated($attachment));
    

Gotchas and Tips

Pitfalls

  1. Disk Configuration:

    • Avoid using disks with existing files (e.g., public) unless you’ve verified they’re attachment-only.
    • Clear the disk before switching to a new one to prevent orphaned files.
  2. Glide Cache:

    • Resized images are cached in storage/app/img. Monitor cache size with:
      php artisan glide:stats
      
    • Clear cache aggressively during development:
      php artisan glide:clear
      
  3. File Naming:

    • Default ReplaceControlCharacters namer may conflict with URLs. Customize via config:
      'file_namers' => [
          \App\FileNamers\CustomNamer::class, // Your custom class
      ],
      
  4. Metadata Retrievers:

    • Imagick requires server support. Fallback to Gd if Imagick fails:
      'metadata_retrievers' => [
          \VanOns\LaravelAttachmentLibrary\Adapters\FileMetadata\GdMetadataAdapter::class => ['image/*'],
      ],
      

Debugging

  • Attachment Not Found:

    • Verify the disk path matches the database path column.
    • Check file permissions on the storage disk.
  • Missing Resized Images:

    • Ensure Glide’s cache_path is writable.
    • Regenerate thumbnails manually:
      Resizer::src($attachment)->regenerate();
      

Extension Points

  1. Custom Attachment Model: Extend \VanOns\LaravelAttachmentLibrary\Models\Attachment and update config:

    'class_mapping' => [
        'attachment' => \App\Models\CustomAttachment::class,
    ],
    
  2. Metadata Providers: Add custom metadata (e.g., EXIF data):

    class ExifMetadataProvider extends MetadataAdapter {
        protected function retrieve(string $path): FileMetadata {
            $exif = exif_read_data($path);
            return new FileMetadata(['exif' => $exif]);
        }
    }
    

    Register in config:

    'metadata_retrievers' => [
        ExifMetadataProvider::class => ['image/jpeg'],
    ],
    
  3. File Namers: Override default naming logic (e.g., UUIDs):

    class UuidFileNamer extends FileNamer {
        public function execute(string $value): string {
            return Str::uuid()->toString();
        }
    }
    

    Configure in attachment-library.php.

Performance

  • Batch Operations: Use sync() instead of attach()/detach() loops for bulk updates.
  • Lazy Loading: Access attachments via with() to avoid N+1 queries:
    $post = Post::with('attachments')->find($id);
    
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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle