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

Flysystem Dropbox V2 Laravel Package

srmklive/flysystem-dropbox-v2

Dropbox V2 adapter for Flysystem, enabling Laravel/PHP apps to store, read, and manage files in Dropbox via the Flysystem filesystem API. Supports common operations like upload/download, listing, deletion, and metadata handling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require srmklive/flysystem-dropbox-v2
    

    Add to config/filesystems.php:

    'dropbox' => [
        'driver' => 'dropbox',
        'key' => env('DROPBOX_KEY'),
        'secret' => env('DROPBOX_SECRET'),
        'token' => env('DROPBOX_TOKEN'),
        'root' => env('DROPBOX_ROOT', '/'), // Optional: Defaults to root
    ],
    
  2. First Use Case Use the Storage facade to interact with Dropbox like a local filesystem:

    use Illuminate\Support\Facades\Storage;
    
    // Upload a file
    Storage::disk('dropbox')->put('path/to/file.txt', 'Content');
    
    // Download a file
    $contents = Storage::disk('dropbox')->get('path/to/file.txt');
    
    // List directory contents
    $files = Storage::disk('dropbox')->files('path/to/directory');
    
  3. Authentication


Implementation Patterns

Common Workflows

  1. File Operations

    • Upload/Download: Use put() and get() for file operations.
      Storage::disk('dropbox')->put('remote/path', $localFile);
      $content = Storage::disk('dropbox')->get('remote/path');
      
    • Streaming: For large files, use streams:
      Storage::disk('dropbox')->writeStream('large-file.txt', fopen('local-file', 'r'));
      
  2. Directory Handling

    • Create Directories: Use mkdir() (Dropbox API v2 doesn’t support nested directories directly; use / separators).
      Storage::disk('dropbox')->mkdir('folder/subfolder');
      
    • List Contents: Use files() or allFiles():
      $files = Storage::disk('dropbox')->files('path/to/dir');
      $allFiles = Storage::disk('dropbox')->allFiles('path/to/dir');
      
  3. Metadata and Permissions

    • File Metadata: Use metadata() to fetch file details:
      $metadata = Storage::disk('dropbox')->metadata('path/to/file');
      
    • Sharing Links: Generate shared links (requires Dropbox Pro/Business):
      $client = Storage::disk('dropbox')->getAdapter()->getClient();
      $link = $client->sharesCreateUrl($metadata['path_display']);
      
  4. Event Handling

    • Listen to file system events (e.g., filesystem.updated):
      Storage::disk('dropbox')->dispatcher()->listen('*', function ($event) {
          // Handle event (e.g., log or trigger actions)
      });
      

Integration Tips

  • Laravel Filesystem Integration: Treat Dropbox like any other filesystem disk. Use Storage::disk('dropbox')-> consistently.
  • Fallback Logic: Combine with local storage for resilience:
    $path = 'file.txt';
    if (Storage::disk('dropbox')->exists($path)) {
        return Storage::disk('dropbox')->get($path);
    }
    return Storage::disk('local')->get($path);
    
  • Batch Operations: Use Dropbox API v2’s batch endpoints for efficiency (requires direct API calls via $adapter->getClient()).

Gotchas and Tips

Pitfalls

  1. API Rate Limits

    • Dropbox API v2 has strict rate limits. Cache metadata and avoid frequent calls to metadata().
    • Workaround: Use lastModified() to check file changes before fetching metadata.
  2. Path Handling

    • Dropbox API v2 uses / as a separator, but ensure paths are normalized:
      $path = str_replace('\\', '/', $path); // Normalize paths
      
    • Gotcha: Trailing slashes in paths may cause issues. Use rtrim($path, '/').
  3. Authentication Expiry

    • OAuth tokens expire. Implement token refresh logic or use Dropbox’s JWT flow for long-lived apps.
    • Tip: Store refresh tokens and implement a dropbox.refresh-token Artisan command.
  4. Large File Handling

    • Files > 150MB require chunked uploads. Use put() with streams or the Dropbox Upload API.
    • Gotcha: Direct put() may fail silently for large files. Validate file size first:
      if (Storage::disk('dropbox')->size('path/to/file') > 150 * 1024 * 1024) {
          // Use chunked upload
      }
      
  5. Permissions and Scopes

    • Ensure your Dropbox app has the correct scopes (e.g., files.metadata.read, files.content.write).
    • Debugging: Check Storage::disk('dropbox')->getAdapter()->getClient()->getLastResponse() for API errors.

Debugging

  • Enable Logging: Add to config/logging.php:

    'channels' => [
        'dropbox' => [
            'driver' => 'single',
            'path' => storage_path('logs/dropbox.log'),
            'level' => 'debug',
        ],
    ],
    

    Then log API responses:

    \Log::channel('dropbox')->debug($adapter->getClient()->getLastResponse());
    
  • Common Errors:

    • 401 Unauthorized: Token expired or invalid. Regenerate tokens.
    • 403 Forbidden: Insufficient permissions. Check scopes.
    • 404 Not Found: Path doesn’t exist. Verify with metadata().

Extension Points

  1. Custom Metadata Extend the adapter to handle custom metadata:

    $adapter = Storage::disk('dropbox')->getAdapter();
    $client = $adapter->getClient();
    $customMetadata = $client->filesUpdate($path, [
        'client_modified' => time(),
        'custom_metadata' => ['key' => 'value'],
    ]);
    
  2. Webhooks Use Dropbox webhooks to trigger Laravel events:

    Route::post('/dropbox/webhook', function (Request $request) {
        event(new DropboxWebhookEvent($request->input()));
    });
    
  3. Flysystem Events Subscribe to Flysystem events for real-time updates:

    Storage::disk('dropbox')->addListener('*', function ($event) {
        // Handle file operations (e.g., sync with a database)
    });
    
  4. Testing Use the dropbox-faker package or mock the adapter:

    $adapter = Mockery::mock(\SR\Dropbox\DropboxAdapter::class);
    Storage::extend('dropbox', function () use ($adapter) {
        return new \League\Flysystem\Filesystem($adapter);
    });
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php