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

Livewire Upload Handler Laravel Package

axn/livewire-upload-handler

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require axn/livewire-upload-handler
    

    Ensure your project meets requirements (PHP 8.4+, Laravel 12+, Livewire 3.1+).

  2. Layout Integration: Add to your Blade layout (preferably app.blade.php):

    <head>
        @livewireStyles
        @livewireUploadHandlerStyles
    </head>
    <body>
        @livewireScripts
        @livewireUploadHandlerScripts
    </body>
    
  3. Git Configuration: Run the provided one-liner to exclude temporary files:

    # Add livewire-tmp/ to storage/app/.gitignore
    if ! grep -q "livewire-tmp/" storage/app/.gitignore 2>/dev/null; then
        echo "livewire-tmp/" >> storage/app/.gitignore
    fi
    
  4. First Upload Component: Use the simplest component for a single file upload:

    <livewire:upload-handler.item />
    

    This renders a drag-and-drop upload area with basic validation.


First Use Case: Basic File Upload

  1. Create a Livewire Component:

    php artisan make:livewire FileUploadDemo
    

    Update the component to use the upload handler:

    // app/Livewire/FileUploadDemo.php
    public function mount()
    {
        $this->uploadHandler = new \AXN\LivewireUploadHandler\UploadHandler();
    }
    
    public function render()
    {
        return view('livewire.file-upload-demo');
    }
    
  2. Blade View:

    <livewire:file-upload-demo />
    
    @push('scripts')
        @livewireScripts
        @livewireUploadHandlerScripts
    @endpush
    
  3. Handle Uploads: Extend the UploadHandler to process files:

    use AXN\LivewireUploadHandler\Events\FileUploaded;
    
    protected function handleFileUploaded(FileUploaded $event)
    {
        // Save to Spatie Media Library or custom logic
        $this->media()->addMedia($event->filePath)->toMediaCollection('uploads');
    }
    

Implementation Patterns

Core Workflows

1. Chunked Uploads for Large Files

  • Setup: Configure chunk size in your component:
    $this->uploadHandler->chunkSize = 5 * 1024 * 1024; // 5MB chunks
    
  • Progress Tracking: Use the progress property to display upload progress:
    <progress value="{{ $uploadHandler->progress }}" max="100"></progress>
    
  • Resume Support: The package automatically handles resuming interrupted uploads via temporary files in storage/app/livewire-tmp/.

2. Image Previews with Glide

  • Auto-Generated Previews: Previews are generated on-the-fly using Glide. No manual intervention required.
  • Custom Preview Paths: Override the preview path in your component:
    $this->uploadHandler->glideCachePath = storage_path('app/.livewire-upload-handler-glide-cache');
    
  • Preview in Blade:
    @if($uploadHandler->hasFiles())
        @foreach($uploadHandler->files as $file)
            <img src="{{ $uploadHandler->getPreviewUrl($file) }}" alt="{{ $file->name }}">
        @endforeach
    @endif
    

3. Spatie Media Library Integration

  • Auto-Save Mode: Enable automatic saving to Spatie Media Library:
    $this->uploadHandler->autoSave = true;
    $this->uploadHandler->mediaCollection = 'user_avatars';
    
  • Manual Mode: Listen for the FileUploaded event and handle manually:
    public function boot()
    {
        FileUploaded::listen(function (FileUploaded $event) {
            $this->media()->addMedia($event->filePath)->toMediaCollection('documents');
        });
    }
    

4. Drag & Drop with Sortable Files

  • Drag-and-Drop Setup: The component includes built-in drag-and-drop. Customize the drop zone:
    <livewire:upload-handler.item
        drop-zone-class="bg-blue-50 p-8 rounded-lg border-2 border-dashed border-blue-300"
        drop-zone-text="Drag & drop files here or click to browse"
    />
    
  • Sortable Files: Enable Sortable.js for reordering:
    $this->uploadHandler->sortable = true;
    
    Update Blade to include Sortable.js:
    @push('scripts')
        <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
        <script>
            document.addEventListener('livewire:init', () => {
                Sortable.create(document.querySelector('.sortable-files'));
            });
        </script>
    @endpush
    

Integration Tips

1. Validation Rules

  • Custom Validation: Extend the UploadHandler to add validation:
    $this->uploadHandler->addValidationRule('max_size', 10 * 1024 * 1024); // 10MB
    $this->uploadHandler->addValidationRule('allowed_types', ['image/jpeg', 'image/png', 'application/pdf']);
    
  • Reuse Existing Laravel Rules: Use Laravel's validation rules via a closure:
    $this->uploadHandler->validationRules = [
        'file.*' => ['required', 'max:10240', function ($attribute, $value, $fail) {
            if (!in_array($value->getClientOriginalExtension(), ['jpg', 'png'])) {
                $fail('Only JPG and PNG files are allowed.');
            }
        }],
    ];
    

2. Theming

  • CSS Classes: Customize appearance via Blade attributes:
    <livewire:upload-handler.item
        upload-button-class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded"
        file-item-class="bg-gray-100 p-2 mb-2 rounded"
    />
    
  • Icons: Use your preferred icon library (e.g., Heroicons, Font Awesome) by overriding the default icons in your component.

3. i18n Support

  • Language Switching: Set the language in your component:
    $this->uploadHandler->setLocale('fr'); // French
    
  • Custom Translations: Publish the language files:
    php artisan vendor:publish --tag=livewire-upload-handler-translations
    
    Then extend resources/lang/vendor/livewire-upload-handler/.

4. Event Handling

  • Listen for Events: Subscribe to built-in events in your component's boot() method:
    public function boot()
    {
        \AXN\LivewireUploadHandler\Events\FileUploaded::listen(function ($event) {
            Log::info('File uploaded: ' . $event->fileName);
        });
    
        \AXN\LivewireUploadHandler\Events\UploadFailed::listen(function ($event) {
            session()->flash('error', 'Upload failed: ' . $event->error);
        });
    }
    

5. Multiple File Uploads

  • Batch Processing: Use the batch property to group uploads:
    $this->uploadHandler->batch = 'user_documents_' . auth()->id();
    
  • Bulk Actions: Implement bulk delete or download:
    @if($uploadHandler->hasFiles())
        <button wire:click="deleteSelected" class="btn-danger">
            Delete Selected
        </button>
    @endif
    
    public function deleteSelected()
    {
        $this->uploadHandler->deleteSelected($this->selectedFiles);
    }
    

Gotchas and Tips

Pitfalls and Debugging

1. Chunked Upload Failures

  • Issue: Uploads fail silently or partially complete.
  • Debugging: Check the livewire-tmp/ directory for incomplete chunks. Ensure:
    • The directory is writable (chmod -R 775 storage/app/livewire-tmp).
    • PHP's upload_max_filesize and post_max_size in php.ini are larger than your chunk size.
    • No firewall or security software is blocking chunked requests.
  • Logs: Enable debug mode in the UploadHandler:
    $this->uploadHandler->debug = true;
    
    Check Laravel logs for chunk-related errors.

2. **Glide

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.
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
atriumphp/atrium