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

league/flysystem

Flysystem is a filesystem abstraction for PHP that lets you read, write, and manage files through a unified API across local disks and cloud storage (S3, FTP, SFTP, etc.). Swap adapters without changing app code, with consistent paths, streams, and visibility.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation:

    composer require league/flysystem
    

    For common adapters (e.g., S3, local):

    composer require league/flysystem-aws-s3-s3v3
    composer require league/flysystem-local
    
  2. Basic Configuration: Define adapters in config/filesystems.php (Laravel already includes FlySystem support):

    'disks' => [
        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],
        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],
    ],
    
  3. First Use Case: Access files via the Storage facade:

    use Illuminate\Support\Facades\Storage;
    
    // Write a file
    Storage::disk('s3')->put('file.txt', 'Hello, FlySystem!');
    
    // Read a file
    $contents = Storage::disk('local')->get('file.txt');
    
    // List files
    $files = Storage::disk('s3')->files('path/to/dir');
    

Implementation Patterns

Core Workflows

  1. File Operations:

    • Upload/Write: Use put(), write(), or writeStream() for files/strings/streaming.
      Storage::disk('s3')->put('report.pdf', $fileContents);
      Storage::disk('local')->write('log.txt', 'New log entry');
      
    • Download/Read: Use get(), read(), or readStream().
      $content = Storage::disk('s3')->get('report.pdf');
      Storage::disk('local')->readStream('log.txt');
      
    • Delete: Use delete() for single files or deleteDirectory() for directories.
      Storage::disk('s3')->delete('old-file.txt');
      Storage::disk('local')->deleteDirectory('temp');
      
  2. Directory Operations:

    • Create/Check: Use makeDirectory() or directoryExists().
      Storage::disk('s3')->makeDirectory('uploads/2023');
      if (Storage::disk('local')->directoryExists('cache')) { ... }
      
    • List Contents: Use files(), directories(), or allFiles().
      $files = Storage::disk('s3')->files('uploads');
      $dirs = Storage::disk('local')->directories('storage');
      
  3. Metadata and URLs:

    • Metadata: Use metadata(), mimeType(), size(), or lastModified().
      $metadata = Storage::disk('s3')->metadata('file.txt');
      $mime = Storage::disk('local')->mimeType('file.txt');
      
    • Public URLs: Use url() or temporaryUrl() (for signed URLs).
      $url = Storage::disk('s3')->url('public/image.jpg');
      $tempUrl = Storage::disk('s3')->temporaryUrl('private/file.pdf', now()->addHours(1));
      
  4. Copy/Move/Rename:

    • Use copy(), move(), or rename() with source/destination paths.
      Storage::disk('s3')->copy('old.txt', 'backup/old.txt');
      Storage::disk('local')->move('file1.txt', 'file2.txt');
      
  5. Checksums:

    • Use checksum() for file integrity verification.
      $checksum = Storage::disk('s3')->checksum('file.txt');
      

Integration Tips

  1. MountManager for Multiple Adapters: Combine adapters (e.g., local fallback for S3):

    use League\Flysystem\MountManager;
    
    $mountManager = new MountManager([
        's3' => new AwsS3Adapter(...),
        'local' => new LocalAdapter(...),
    ]);
    $mountManager->mount('backup', $mountManager->getAdapter('local'));
    
  2. Decorators for Extensions: Extend functionality with decorators (e.g., logging, caching):

    use League\Flysystem\Cached\CachedAdapter;
    use League\Flysystem\Cached\Storage\FilesystemAdapterStorage;
    
    $cache = new FilesystemAdapterStorage(storage_path('cache/flysystem'));
    $adapter = new CachedAdapter($s3Adapter, $cache);
    
  3. Async Operations: Use AsyncAwsS3Adapter for non-blocking S3 operations:

    $asyncAdapter = new AsyncAwsS3Adapter($asyncAwsS3Client, 'bucket');
    
  4. Visibility and Permissions: Configure visibility (e.g., public, private) during uploads:

    Storage::disk('s3')->put('file.txt', 'content', [
        'visibility' => 'public',
    ]);
    
  5. Streaming Large Files: Use writeStream()/readStream() for memory efficiency:

    Storage::disk('s3')->writeStream('large-video.mp4', fopen('local-video.mp4', 'r'));
    

Gotchas and Tips

Common Pitfalls

  1. Path Handling:

    • Trailing Slashes: FlySystem normalizes paths, but ensure consistency (e.g., 'dir/' vs 'dir').
    • Root Directory: Local adapters may require explicit root paths (e.g., storage_path('app')).
    • Prefixing: Use PathPrefixingAdapter to add prefixes to all paths:
      $adapter = new PathPrefixingAdapter($localAdapter, 'prefix/');
      
  2. Visibility and Permissions:

    • S3 Visibility: Defaults to private. Explicitly set visibility in options:
      Storage::disk('s3')->put('file.txt', 'content', ['visibility' => 'public']);
      
    • Local Files: Visibility is ignored unless using LocalAdapter with visibility config.
  3. Directory Listing Quirks:

    • Empty Directories: Some adapters (e.g., S3) may not list empty directories. Use allFiles() to include hidden files.
    • Filtering: Use files()/directories() with glob patterns:
      $files = Storage::disk('s3')->files('*.jpg');
      
  4. Checksums:

    • Unsupported Adapters: Not all adapters support checksums (e.g., InMemory). Fall back to ad-hoc generation:
      try {
          $checksum = Storage::disk('s3')->checksum('file.txt');
      } catch (\League\Flysystem\ChecksumAlgoIsNotSupported) {
          $checksum = md5(Storage::disk('s3')->read('file.txt'));
      }
      
  5. Connection Management:

    • SFTP/FTP: Always call disconnect() to free resources:
      $sftpAdapter->disconnect();
      
    • S3: Configure timeouts and retries in the AWS SDK.
  6. Temporary URLs:

    • Expiration: Temporary URLs expire. Use temporaryUrl() with a Carbon timestamp:
      $url = Storage::disk('s3')->temporaryUrl('file.pdf', now()->addMinutes(30));
      
    • Permissions: Ensure the IAM role has s3:GetObject permissions.
  7. Race Conditions:

    • Directory Creation: Use makeDirectory() with recursive: true to avoid race conditions:
      Storage::disk('s3')->makeDirectory('path/to/dir', 0777, true);
      

Debugging Tips

  1. Enable Debugging:

    • Set debug: true in adapter configs (e.g., SFTP) to log connection issues.
  2. Handle Exceptions:

    • Catch specific exceptions (e.g., League\Flysystem\UnableToReadFile, League\Flysystem\ConnectionException):
      try {
          Storage::disk('s3')->get('file.txt');
      } catch (\League\Flysystem\FileNotFoundException $e) {
          Log::error('File not found: ' . $e->getMessage());
      }
      
  3. Adapter-Specific Issues:

    • S3: Use ListObjectsV2 for large directories (avoids pagination limits).
    • SFTP: Ensure the server supports the SSH algorithm (e.g., ssh-rsa).
    • Local: Check file permissions (e.g., chmod -R 777 storage).
  4. Logging:

    • Use Laravel’s logging to trace Fly
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.
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
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai