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

Laravel Google Cloud Storage Laravel Package

spatie/laravel-google-cloud-storage

Laravel 9+ Google Cloud Storage filesystem driver using Flysystem v3 and a dedicated GCS adapter. Adds a gcs disk with service account key file/array support, project and bucket config, path prefixes, endpoints, and public/private visibility options.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-google-cloud-storage
    

    Publish the config file:

    php artisan vendor:publish --provider="Spatie\GoogleCloudStorage\GoogleCloudStorageServiceProvider" --tag="google-cloud-storage-config"
    
  2. Configuration:

    • Add your Google Cloud credentials (JSON key file) to .env:
      GOOGLE_CLOUD_STORAGE_KEY_FILE=/path/to/your/service-account-key.json
      GOOGLE_CLOUD_STORAGE_BUCKET=your-bucket-name
      
    • Configure the filesystem in config/filesystems.php:
      'disks' => [
          'gcs' => [
              'driver' => 'google',
              'bucket' => env('GOOGLE_CLOUD_STORAGE_BUCKET'),
              'project_id' => env('GOOGLE_CLOUD_STORAGE_PROJECT_ID', 'your-project-id'),
              'key_file' => env('GOOGLE_CLOUD_STORAGE_KEY_FILE'),
              'root' => env('GOOGLE_CLOUD_STORAGE_ROOT', ''),
              'throw' => env('GOOGLE_CLOUD_STORAGE_THROW', false),
          ],
      ],
      
  3. First Use Case: Upload a file using Laravel’s built-in Storage facade:

    use Illuminate\Support\Facades\Storage;
    
    Storage::disk('gcs')->put('path/to/file.txt', 'file contents');
    

Implementation Patterns

Core Workflows

  1. File Operations:

    • Use Laravel’s Storage facade for consistency:
      // Upload
      Storage::disk('gcs')->put('file.jpg', file_get_contents('local.jpg'));
      
      // Download
      $contents = Storage::disk('gcs')->get('file.jpg');
      
      // Delete
      Storage::disk('gcs')->delete('file.jpg');
      
  2. Directory Handling:

    • Create directories recursively:
      Storage::disk('gcs')->makeDirectory('folders/subfolder');
      
    • List files in a directory:
      $files = Storage::disk('gcs')->files('folder/');
      
  3. URL Generation:

    • Generate public URLs for files:
      $url = Storage::disk('gcs')->url('file.jpg');
      
    • Configure CORS or ACLs for public access via Google Cloud Console.
  4. Temporary Files:

    • Use temporaryUrl() for time-limited access:
      $url = Storage::disk('gcs')->temporaryUrl('file.jpg', now()->addMinutes(15));
      

Integration Tips

  • Laravel Filesystem Integration: Leverage Laravel’s Storage facade for seamless integration with existing code (e.g., Storage::put(), Storage::disk()).
  • Media Library Packages: Works out-of-the-box with packages like spatie/laravel-medialibrary or intervention/image:
    $image = Image::make('local.jpg')->resize(300, 200);
    Storage::disk('gcs')->put('resized.jpg', $image->stream());
    
  • Queue Jobs for Large Uploads: Offload heavy uploads to queues to avoid timeouts:
    dispatch(new UploadToGCSJob($filePath, 'gcs'));
    
  • Environment-Specific Configs: Use Laravel’s config() helper to dynamically switch buckets:
    $disk = config('app.env') === 'production' ? 'gcs_prod' : 'gcs_dev';
    Storage::disk($disk)->put(...);
    

Gotchas and Tips

Pitfalls

  1. Permission Issues:

    • Ensure the service account has Storage Admin or Storage Object Admin roles in Google Cloud IAM.
    • Debug Tip: Check logs with GOOGLE_CLOUD_STORAGE_THROW=true in .env to surface permission errors.
  2. Bucket Naming:

    • Buckets must be globally unique across all Google Cloud projects. Avoid hardcoding names; use .env.
  3. CORS Configuration:

    • If accessing files via URLs, configure CORS in Google Cloud Console. Test with:
      curl -I https://storage.googleapis.com/your-bucket/file.jpg
      
  4. Large File Uploads:

    • Google Cloud Storage has a default chunk size of 5MB. For larger files, use resumable uploads or chunked uploads via the SDK:
      use Google\Cloud\Storage\StorageClient;
      $storage = new StorageClient();
      $bucket = $storage->bucket('your-bucket');
      $object = $bucket->upload(
          fopen('large-file.zip', 'r'),
          ['name' => 'large-file.zip']
      );
      
  5. Timeouts:

    • Long-running operations (e.g., listing large directories) may timeout. Use Storage::disk()->listContents() with pagination:
      $objects = Storage::disk('gcs')->listContents('folder/', false);
      

Debugging

  • Enable Debugging: Set GOOGLE_CLOUD_STORAGE_THROW=true to convert exceptions to HTTP errors.
  • Log Levels: Adjust logging in config/google-cloud-storage.php:
    'logging' => [
        'enabled' => env('GOOGLE_CLOUD_STORAGE_LOGGING', false),
        'level' => env('GOOGLE_CLOUD_STORAGE_LOG_LEVEL', 'info'),
    ],
    
  • SDK Debugging: Use the underlying SDK for low-level debugging:
    use Google\Cloud\Storage\StorageClient;
    $storage = new StorageClient(['logging' => ['debug' => true]]);
    

Extension Points

  1. Custom Metadata: Add metadata during upload:

    Storage::disk('gcs')->put('file.jpg', $contents, [
        'metadata' => [
            'customKey' => 'customValue',
            'contentType' => 'image/jpeg',
        ],
    ]);
    
  2. Event Listeners: Listen to file system events (e.g., Storage::disk('gcs')->put()) via Laravel’s Storage events:

    Storage::disk('gcs')->put('file.jpg', $contents);
    // Triggered via event: 'storage:file:created'
    
  3. Flysystem Adapter: Access the underlying Flysystem adapter for advanced operations:

    $adapter = Storage::disk('gcs')->getAdapter();
    $adapter->writeStream('file.txt', fopen('local.txt', 'r'));
    
  4. Retry Logic: Implement custom retry logic for transient failures:

    use Spatie\GoogleCloudStorage\GoogleCloudStorage;
    $gcs = new GoogleCloudStorage();
    $gcs->withRetry(3, 100)->put(...);
    
  5. Local Testing: Use google-cloud-storage’s local emulator for testing:

    docker run -p 4443:4443 gcr.io/google.com/cloudsdktool/google-cloud-cli
    

    Configure .env to point to the emulator:

    GOOGLE_CLOUD_STORAGE_EMULATOR_HOST=localhost:4443
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport