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

nao-pon/flysystem-google-drive

Laravel Flysystem adapter for Google Drive. Store, read, list, update and delete files on Drive using Flysystem’s filesystem API, with support for service accounts or OAuth. Ideal for using Google Drive as a cloud disk in Laravel apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require nao-pon/flysystem-google-drive
    

    Ensure league/flysystem is also installed (dependency).

  2. Configure Google Drive Credentials

    • Obtain OAuth 2.0 credentials from Google Cloud Console.
    • Store the client_id, client_secret, and redirect_uri in .env:
      GOOGLE_DRIVE_CLIENT_ID=your_client_id
      GOOGLE_DRIVE_CLIENT_SECRET=your_client_secret
      GOOGLE_DRIVE_REDIRECT_URI=http://localhost/callback
      
  3. Basic Adapter Initialization

    use NaoPon\FlysystemGoogleDrive\GoogleDriveAdapter;
    
    $adapter = new GoogleDriveAdapter(
        $clientId,
        $clientSecret,
        $redirectUri,
        $accessToken // Optional: Pre-authenticated token
    );
    
    $filesystem = new \League\Flysystem\Filesystem($adapter);
    
  4. First Use Case: Upload a File

    $filesystem->write('folder/file.txt', 'Hello, Google Drive!');
    

Implementation Patterns

Authentication Workflows

  • OAuth Flow: Use the GoogleDriveAdapter with a redirect URI to initiate OAuth. Handle the callback in a Laravel route:
    Route::get('/callback', function () {
        $adapter = new GoogleDriveAdapter(
            config('services.google.client_id'),
            config('services.google.client_secret'),
            config('services.google.redirect_uri')
        );
        $authUrl = $adapter->getAuthUrl();
        // Redirect user to $authUrl, then handle the token exchange.
    });
    
  • Service Account (Non-Interactive): For server-to-server use, generate a service account JSON key and pass it:
    $adapter = new GoogleDriveAdapter(
        null, // No OAuth for service accounts
        null,
        null,
        null,
        $serviceAccountJsonPath
    );
    

Common Operations

  • Streaming Large Files: Use writeStream() to avoid memory issues:
    $filesystem->writeStream('large-file.zip', fopen('local-file.zip', 'r'));
    
  • Directory Handling: Google Drive lacks traditional directories; use folder IDs:
    $filesystem->createDirectory('folder-id'); // 'folder-id' is a Google Drive folder ID
    
  • Metadata Management: Retrieve file metadata (e.g., size, MIME type):
    $metadata = $filesystem->metadata('file-id');
    

Integration with Laravel

  • Filesystem Disk: Register the adapter as a Laravel disk in config/filesystems.php:
    'disks' => [
        'google' => [
            'driver' => 'google',
            'client_id' => env('GOOGLE_DRIVE_CLIENT_ID'),
            'client_secret' => env('GOOGLE_DRIVE_CLIENT_SECRET'),
            'redirect_uri' => env('GOOGLE_DRIVE_REDIRECT_URI'),
            'access_token' => env('GOOGLE_DRIVE_ACCESS_TOKEN'),
        ],
    ],
    
    Then use it like any other disk:
    Storage::disk('google')->put('file.txt', 'Content');
    

Gotchas and Tips

Pitfalls

  1. OAuth Token Expiry: Tokens expire (~1 hour). Implement token refresh logic or use a library like google/apiclient for automatic handling.
  2. Folder vs. File IDs: Google Drive uses IDs, not paths. Ensure you’re working with IDs (e.g., 1AbCdEfGhIjKlMnOpQrStUvWxYz) rather than paths.
  3. Permissions: Ensure the authenticated user has access to the target files/folders. Test with a service account for CI/CD pipelines.
  4. Rate Limits: Google Drive has quotas (e.g., 1,000 API calls/minute). Batch operations where possible.

Debugging

  • Enable Logging: Set the debug option in the adapter constructor to log API requests:
    $adapter = new GoogleDriveAdapter(..., ..., ..., true);
    
  • Check HTTP Errors: Wrap operations in try-catch to inspect Google_Service_Exception for API errors.

Extension Points

  1. Custom Metadata: Extend the adapter to handle custom metadata fields by overriding getMetadata().
  2. Event Listeners: Use Laravel’s events to trigger actions on file operations (e.g., filesystem.storing).
  3. Fallback Storage: Combine with other Flysystem adapters for hybrid storage:
$local = new \League\Flysystem\Local\LocalFilesystemAdapter('/local/path');
$google = new GoogleDriveAdapter(...);
$composite = new \League\Flysystem\CompositeFilesystem([$local, $google]);

Pro Tips

  • Use visibility Option: Set file visibility (e.g., 'visibility' => 'private') during uploads.
  • Leverage Google Drive API Features: Access advanced features like sharing or versioning via the underlying Google_Service_Drive client:
    $client = $adapter->getClient();
    $permissions = $client->permissions->listPermissions('file-id');
    
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/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
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
agtp/mod-php
splash/sonata-admin