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

Cloud Storage Laravel Package

google/cloud-storage

Idiomatic PHP client for Google Cloud Storage. Upload/download objects, manage buckets and permissions (ACLs), use a gs:// stream wrapper, and integrate with Google Cloud PHP authentication. Great for backups, archival, and serving large files.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require google/cloud-storage
    

    Add to composer.json under require or require-dev based on your needs.

  2. Authentication:

    • Use Application Default Credentials (ADC) for local/dev:
      gcloud auth application-default login
      
    • For production, configure a service account key in .env:
      GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
      
    • Verify credentials via:
      use Google\Auth\ApplicationDefaultCredentials;
      $credentials = ApplicationDefaultCredentials::getCredentials();
      
  3. First Use Case: Upload a file to a bucket with public access:

    use Google\Cloud\Storage\StorageClient;
    
    $storage = new StorageClient();
    $bucket = $storage->bucket('my-bucket-name');
    
    $bucket->upload(
        fopen('/path/to/local/file.txt', 'r'),
        ['predefinedAcl' => 'publicRead']
    );
    
  4. Key Files:


Implementation Patterns

Core Workflows

1. Bucket Management

  • Create/Delete Buckets:
    $bucket = $storage->createBucket('new-bucket-name', [
        'storageClass' => 'STANDARD',
        'location' => 'US',
    ]);
    $bucket->delete();
    
  • List Buckets:
    foreach ($storage->buckets() as $bucket) {
        echo $bucket->name() . "\n";
    }
    

2. Object Operations

  • Upload/Download:
    // Upload from file
    $bucket->upload(fopen('local.txt', 'r'));
    
    // Download to file
    $object = $bucket->object('remote.txt');
    $object->downloadToFile('local_copy.txt');
    
  • Streaming with gs:// Wrapper:
    $storage->registerStreamWrapper();
    $contents = file_get_contents('gs://my-bucket/file.txt');
    

3. Metadata & ACLs

  • Set Metadata:
    $object->update([
        'metadata' => [
            'author' => 'John Doe',
            'description' => 'Sample file',
        ],
    ]);
    
  • Predefined ACLs:
    $bucket->upload(fopen('file.txt', 'r'), [
        'predefinedAcl' => 'publicRead', // or 'authenticatedRead', 'private'
    ]);
    

4. Lifecycle & Retention

  • Soft Delete & Retention:
    $bucket->update([
        'retentionPeriod' => 365, // days
        'retentionEffectiveTime' => new DateTime('now'),
    ]);
    
  • Lifecycle Rules:
    $bucket->update([
        'lifecycleRules' => [
            [
                'action' => ['type' => 'SetStorageClass', 'storageClass' => 'COLDLINE'],
                'condition' => ['age' => 90],
            ],
        ],
    ]);
    

5. Signed URLs & Temporary Access

  • Generate Signed URL:
    $url = $object->signedUrl(new DateTime('+1 hour'));
    // Use $url to share access without exposing credentials
    

6. Batch Operations

  • Iterate Over Objects:
    foreach ($bucket->objects() as $object) {
        echo $object->name() . "\n";
    }
    
  • Parallel Uploads/Downloads: Use SplObjectStorage or ReactPHP for concurrent operations:
    $loop = React\EventLoop\Factory::create();
    $connector = new React\Socket\Connector($loop);
    // Integrate with google/cloud-storage streams for async I/O
    

Integration Tips

Laravel-Specific Patterns

  1. Service Provider Binding:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(StorageClient::class, function ($app) {
            return new StorageClient([
                'keyFilePath' => $app['config']['services.google.key_file'],
            ]);
        });
    }
    
  2. Configurable Bucket Names:

    // config/services.php
    'google' => [
        'storage' => [
            'default_bucket' => env('GOOGLE_STORAGE_BUCKET', 'default-bucket'),
        ],
    ];
    
  3. Facade for Convenience:

    // app/Facades/GoogleStorage.php
    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class GoogleStorage extends Facade
    {
        protected static function getFacadeAccessor()
        {
            return 'google.storage';
        }
    }
    
  4. File Upload Middleware:

    // app/Http/Middleware/UploadToGCS.php
    public function handle($request, Closure $next)
    {
        if ($request->hasFile('avatar')) {
            $storage = app(StorageClient::class);
            $bucket = $storage->bucket(config('google.storage.default_bucket'));
            $bucket->upload($request->file('avatar')->getRealPath());
        }
        return $next($request);
    }
    
  5. Event-Driven Workflows: Use Laravel Events + Google Cloud Pub/Sub to trigger actions on uploads:

    // Listen for file uploads and process via queue
    event(new FileUploaded($filePath));
    

Gotchas and Tips

Pitfalls

  1. Authentication Issues:

    • Symptom: Google\Auth\Exception\GoogleAuthException
    • Fix: Ensure GOOGLE_APPLICATION_CREDENTIALS is set or ADC is configured. For Laravel, use google/cloud-core for unified auth:
      use Google\Auth\Credentials\ServiceAccountCredentials;
      $credentials = ServiceAccountCredentials::fromKeyFile(
          $keyFilePath,
          ['scopes' => [Storage::SCOPE_CLOUD_PLATFORM]]
      );
      $storage = new StorageClient(['credentials' => $credentials]);
      
  2. Stream Wrapper Quirks:

    • Issue: file_get_contents('gs://...') fails with InvalidArgumentException.
    • Fix: Register the wrapper before using it:
      $storage->registerStreamWrapper();
      
    • Note: The wrapper requires the bucket/object to exist. Use touch() to create empty objects:
      $object = $bucket->object('empty.txt');
      $object->update(['contentType' => 'text/plain']);
      $object->touch();
      
  3. Deprecated Options:

    • Avoid keyFile/keyFilePath in newer versions (marked deprecated in v1.48.4). Use credentials instead:
      $storage = new StorageClient([
          'credentials' => $credentials,
      ]);
      
  4. Path Traversal:

    • Risk: Malicious paths like gs://bucket/../../../etc/passwd.
    • Mitigation: Validate paths server-side or use the package’s built-in containment checks (enabled by default since v1.48.5).
  5. Soft Delete Confusion:

    • Objects marked for soft delete are not immediately deleted. Use restore() or undelete():
      $object->restore(); // Recover from soft delete
      $object->undelete(); // Same as restore()
      
  6. Retry Behavior:

    • Default retries are enabled but configurable. For custom retries:
      $storage = new StorageClient([
          'retry' => [
              'max_attempts' => 3,
              'timeout' => 30.0,
          ],
      ]);
      
  7. Hierarchical Namespace (HNS):

    • Enabled by default in newer versions. For legacy buckets, explicitly disable:
      $bucket = $storage->bucket('legacy-bucket', [
          'hierarchicalNamespace' => false,
      ]);
      

Debugging Tips

  1. Enable Debug Logging:

    putenv('GOOGLE_CLOUD_DEBUG=1');
    // Or set in .env:
    // GOOGLE_CLOUD_DEBUG=1
    

    Logs will appear in stderr or Laravel’s log channel.

  2. Validate API Responses:

    • Check getMetadata() for HTTP status codes:
      $object->update(['metadata' => [...]]);
      $metadata = $object->getMetadata();
      if ($metadata['http
      
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