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
    
    • Publishes migrations, config, and assets.
  2. Configure Disk (optional): Set ATTACHMENTS_DISK in .env to specify a dedicated disk (e.g., ATTACHMENTS_DISK=attachments).

  3. Enable Attachments on a 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 an attachment via the AttachmentManager facade:

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

Implementation Patterns

Core Workflows

  1. Uploading Files:

    $attachment = AttachmentManager::upload($file, [
        'directory' => 'posts/' . $post->id,
        'metadata' => ['user_id' => auth()->id()],
    ]);
    
    • Supports custom directories, metadata, and validation.
  2. Managing Attachments:

    // Move attachment
    AttachmentManager::move($attachment, 'new/directory');
    
    // Rename attachment
    AttachmentManager::rename($attachment, 'new_filename.ext');
    
    // Delete attachment
    AttachmentManager::delete($attachment);
    
  3. Directory Management:

    // Create directory
    AttachmentManager::createDirectory('user_uploads/' . auth()->id());
    
    // Delete directory (recursively)
    AttachmentManager::deleteDirectory('old_uploads');
    
  4. Image Resizing:

    // Blade component (responsive)
    <x-laravel-attachment-library-image :src="$image" size="medium" />
    
    // Manual resizing
    $resized = Resizer::src($image)->width(300)->height(200)->resize();
    

Integration Tips

  • Form Requests: Validate files before upload:

    public function rules()
    {
        return [
            'document' => 'required|file|mimes:pdf,docx|max:10240',
        ];
    }
    
  • Model Observers: Sync attachments on model events:

    class PostObserver
    {
        public function deleted(Post $post)
        {
            $post->attachments()->each->delete();
        }
    }
    
  • API Responses: Serialize attachments with API resources:

    public function toArray($request)
    {
        return [
            'attachments' => $this->attachments->map(fn ($a) => [
                'url' => $a->url,
                'size' => $a->size,
            ]),
        ];
    }
    

Gotchas and Tips

Pitfalls

  1. Disk Configuration:

    • Ensure the disk (ATTACHMENTS_DISK) exists in filesystems.php and is not shared with other files.
    • Example:
      'disks' => [
          'attachments' => [
              'driver' => 'local',
              'root' => storage_path('app/attachments'),
          ],
      ],
      
  2. Glide Cache:

    • Clear Glide cache after major updates:
      php artisan glide:clear
      
    • Monitor cache size with:
      php artisan glide:stats
      
  3. File Naming:

    • Default ReplaceControlCharacters namer may conflict with special characters. Extend or override:
      // config/attachment-library.php
      'file_namers' => [
          \App\FileNamers\CustomNamer::class,
      ],
      
  4. Metadata Retrievers:

    • Imagick may fail on shared hosting. Fallback to Gd:
      'metadata_retrievers' => [
          \VanOns\LaravelAttachmentLibrary\Adapters\FileMetadata\GdMetadataAdapter::class => ['image/*'],
      ],
      

Debugging

  • Attachment Not Found: Verify the disk path and file permissions. Check the attachments table for correct path and disk values.

  • Missing URLs: Ensure the url column in the attachments table is populated. Use:

    $attachment->refreshUrl(); // Force URL regeneration
    
  • Glide Errors: Validate glide.php config (e.g., cache_path, source_path). Test with:

    php artisan glide:test
    

Extension Points

  1. Custom Attachment Model: Extend the base Attachment model:

    class CustomAttachment extends \VanOns\LaravelAttachmentLibrary\Models\Attachment
    {
        protected $casts = [
            'custom_field' => 'boolean',
        ];
    }
    

    Update config:

    'class_mapping' => [
        'attachment' => \App\Models\CustomAttachment::class,
    ],
    
  2. Custom File Namers: Implement FileNamer for unique naming logic:

    class UuidFileNamer extends \VanOns\LaravelAttachmentLibrary\FileNamers\FileNamer
    {
        public function execute(string $value): string
        {
            return Str::uuid() . '.' . pathinfo($value, PATHINFO_EXTENSION);
        }
    }
    
  3. Metadata Adapters: Add support for new file types (e.g., PDFs):

    class PdfMetadataAdapter extends \VanOns\LaravelAttachmentLibrary\Adapters\FileMetadata\MetadataAdapter
    {
        protected function retrieve(string $path): ?FileMetadata
        {
            $pdf = \Spatie\PdfToText\Pdf::load($path);
            return new FileMetadata(['pages' => $pdf->pageCount()]);
        }
    }
    

    Register in config:

    'metadata_retrievers' => [
        \App\Adapters\PdfMetadataAdapter::class => ['application/pdf'],
    ],
    
  4. Events: Listen for attachment events (e.g., AttachmentCreated):

    Attachment::created(function ($attachment) {
        // Send notification or log
    });
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky