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 Dropzone Laravel Package

dasundev/livewire-dropzone

Livewire Dropzone adds an easy drag-and-drop upload area to Laravel Livewire apps. Supports simple file selection and drop uploads with a reusable component, helping you build modern upload UX quickly with minimal setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dasundev/livewire-dropzone
    

    Publish assets (if needed):

    npm install && npm run dev
    
  2. Basic Usage: Create a Livewire component:

    php artisan make:livewire FileUpload
    

    Add the Dropzone component to your Blade view:

    <livewire:file-upload />
    

    Implement the component logic:

    // app/Http/Livewire/FileUpload.php
    use DasunDev\LivewireDropzone\LivewireDropzone;
    
    public function mount()
    {
        $this->file = null;
    }
    
    public function updated($propertyName)
    {
        $this->validateOnly($propertyName, [
            'file' => 'nullable|array',
            'file.*' => 'image|mimes:jpeg,png,jpg,gif|max:1024',
        ]);
    }
    
    public function render()
    {
        return view('livewire.file-upload', [
            'files' => $this->file,
        ]);
    }
    
  3. View Integration:

    <livewire-dropzone
        wire:model="file"
        upload-url="{{ route('upload') }}"
        max-files="1"
        accept="image/*"
    />
    

First Use Case

Replace traditional file inputs with a seamless drag-and-drop interface for image uploads in a user profile component.


Implementation Patterns

Core Workflows

1. Single File Upload

<livewire-dropzone
    wire:model="profileImage"
    upload-url="{{ route('profile.upload') }}"
    max-files="1"
    accept="image/*"
    with-credentials="true"
/>

2. Multiple File Handling

// Component
public $files = [];

public function updated($propertyName)
{
    $this->validateOnly($propertyName, [
        'files' => 'nullable|array',
        'files.*' => 'file|max:1024',
    ]);
}
<livewire-dropzone
    wire:model="files"
    upload-url="{{ route('files.upload') }}"
    max-files="5"
    accept="image/*,application/pdf"
/>

3. File Processing

protected $rules = [
    'file' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
];

public function upload()
{
    if ($this->validate()) {
        $path = $this->file->store('uploads');
        // Process file (e.g., generate thumbnail)
        event(new FileUploaded($this->file, $path));
    }
}

4. Dynamic Configuration

<livewire-dropzone
    :config="dropzoneConfig"
    wire:model="documents"
/>
// Component
public function getDropzoneConfigProperty()
{
    return [
        'url' => route('documents.upload'),
        'maxFilesize' => 5, // MB
        'acceptedFiles' => 'application/pdf,image/*',
        'autoProcessQueue' => true,
    ];
}

Integration Tips

Livewire Hooks

protected $listeners = ['fileUploaded' => 'handleUpload'];

public function handleUpload($event)
{
    $this->emit('alert', 'File uploaded successfully!');
}

File Validation

public function updated($propertyName)
{
    $this->validateOnly($propertyName, [
        'file' => [
            'required',
            'file',
            Rule::unique('media')->where(fn ($query) => $query->where('model_type', self::class)),
        ],
    ]);
}

Custom Events

// Dispatch from component
$this->emit('fileUploadProgress', $percentage);

// Listen in parent component
protected $listeners = ['fileUploadProgress' => 'updateProgress'];

Chunked Uploads

// Component
public function updated($propertyName)
{
    $this->validateOnly($propertyName, [
        'file' => 'required|file|max:10240', // 10MB
    ]);

    if ($this->file) {
        $chunkSize = 2 * 1024 * 1024; // 2MB chunks
        $this->uploadInChunks($this->file->path(), $chunkSize);
    }
}

Gotchas and Tips

Common Pitfalls

  1. CSRF Token Mismatch

    • Ensure your upload URL includes @csrf token if using traditional form submission:
      <livewire-dropzone
          upload-url="{{ route('upload') }}?{{ csrf_token() }}"
      />
      
  2. File Size Limits

    • PHP post_max_size and upload_max_filesize must exceed your Dropzone limits:
      ; php.ini
      upload_max_filesize = 20M
      post_max_size = 25M
      
  3. Multiple Dropzones on Page

    • Always set unique-id to avoid event conflicts:
      <livewire-dropzone unique-id="profile-upload" ... />
      
  4. Temporary File Cleanup

    • Files uploaded via Dropzone are stored temporarily. Ensure your storage driver handles cleanup:
      // After processing
      Storage::delete($tempPath);
      

Debugging Tips

  1. Network Tab Inspection

    • Check the X-Requested-With: Livewire header in browser dev tools to verify Livewire requests.
  2. Event Listening

    • Use wire:ignore on parent containers to prevent event bubbling issues:
      <div wire:ignore>
          <livewire-dropzone ... />
      </div>
      
  3. Validation Errors

    • Validate in updated() method to show errors immediately:
      public function updated($propertyName)
      {
          $this->validateOnly($propertyName, [
              'file' => 'required|mimes:jpeg,png|max:1024',
          ]);
      }
      

Configuration Quirks

  1. Custom Upload URLs

    • For API endpoints, use absolute URLs:
      <livewire-dropzone upload-url="{{ config('app.url').'/api/upload' }}" />
      
  2. CORS Issues

    • If using external upload endpoints, configure CORS headers:
      // Middleware
      $response->header('Access-Control-Allow-Origin', '*');
      $response->header('Access-Control-Allow-Methods', 'POST, OPTIONS');
      
  3. File Preview Limitations

    • For large files (>5MB), disable preview to improve performance:
      <livewire-dropzone preview="false" ... />
      

Extension Points

  1. Custom Templates

    • Override the default template by publishing views:
      php artisan vendor:publish --tag=livewire-dropzone-views
      
    • Modify resources/views/vendor/livewire-dropzone/dropzone.blade.php.
  2. Alpine.js Integration

    • Extend functionality with Alpine directives:
      <livewire-dropzone
          x-data="{ isProcessing: false }"
          @processing.window="isProcessing = true"
          @complete.window="isProcessing = false"
      />
      
  3. Progress Tracking

    // Component
    public $uploadProgress = 0;
    
    public function updated($propertyName)
    {
        $this->validateOnly($propertyName, [...]);
    
        if ($this->file) {
            $this->uploadProgress = 0;
            $this->emit('uploadStarted');
        }
    }
    
    // Blade
    <progress x-show="isProcessing" :value="uploadProgress" max="100">
        {{ uploadProgress }}%
    </progress>
    
  4. File Metadata

    • Access original file metadata in updated():
      public function updated($propertyName)
      {
          if ($this->file) {
              $file = $this->file[0];
              $this->emit('fileMetadata', [
                  'name' => $file->getClientOriginalName(),
                  'size' => $file->getSize(),
                  'mime' => $file->getMimeType(),
              ]);
          }
      }
      
  5. Fallback for Old Browsers

    @if(config('app.debug'))
        <livewire-dropzone ... />
    @else
        <input type="file" wire:model="file" />
    @endif
    
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.
bugban/php-sdk
littlerocket/job-queue-bundle
graham-campbell/flysystem
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/opensearch-client
directorytree/opensearch-adapter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php