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

S3 Laravel Package

async-aws/s3

AsyncAws S3 is a lightweight, async-friendly AWS S3 API client for PHP. Install via Composer and use it to upload, download, list, and manage buckets and objects with a modern, typed client. Part of the AsyncAws suite.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require async-aws/s3
    
  2. Basic Client Initialization:

    use AsyncAws\S3\S3Client;
    
    $client = new S3Client([
        'region' => 'us-east-1',
        'version' => 'latest',
        'credentials' => [
            'key' => 'YOUR_ACCESS_KEY',
            'secret' => 'YOUR_SECRET_KEY',
        ],
    ]);
    
  3. First Use Case: Upload a file to S3:

    $result = $client->putObject([
        'Bucket' => 'your-bucket-name',
        'Key' => 'path/to/file.txt',
        'Body' => fopen('local-file.txt', 'r'),
    ]);
    

Where to Look First

  • Official Documentation: AsyncAws S3 Client
  • Source Code: Focus on src/Input/ for request objects and src/Result/ for response objects.
  • Changelog: Review recent updates for new features (e.g., checksum algorithms, regions).

Implementation Patterns

Common Workflows

1. File Upload/Download

  • Upload:
    $client->putObject([
        'Bucket' => 'bucket-name',
        'Key' => 'file.txt',
        'Body' => fopen('local-file.txt', 'r'),
        'ACL' => 'public-read', // Optional
    ]);
    
  • Download:
    $result = $client->getObject([
        'Bucket' => 'bucket-name',
        'Key' => 'file.txt',
    ]);
    file_put_contents('downloaded-file.txt', $result->getBody()->getContents());
    

2. Handling Large Files (Multipart Upload)

$uploadId = $client->createMultipartUpload([
    'Bucket' => 'bucket-name',
    'Key' => 'large-file.txt',
]);

$parts = [];
$file = fopen('large-file.txt', 'r');
while (!feof($file)) {
    $part = $client->uploadPart([
        'Bucket' => 'bucket-name',
        'Key' => 'large-file.txt',
        'UploadId' => $uploadId,
        'Body' => fread($file, 5 * 1024 * 1024), // 5MB chunks
    ]);
    $parts[] = $part;
}

$client->completeMultipartUpload([
    'Bucket' => 'bucket-name',
    'Key' => 'large-file.txt',
    'UploadId' => $uploadId,
    'MultipartUpload' => ['Parts' => $parts],
]);

3. Bucket Operations

  • Create Bucket:
    $client->createBucket(['Bucket' => 'new-bucket-name']);
    
  • List Buckets:
    $buckets = $client->listBuckets();
    foreach ($buckets->getBuckets() as $bucket) {
        echo $bucket->getName();
    }
    

4. Lifecycle and Versioning

  • Enable Versioning:
    $client->putBucketVersioning([
        'Bucket' => 'bucket-name',
        'VersioningConfiguration' => ['Status' => 'Enabled'],
    ]);
    
  • Set Lifecycle Rules:
    $client->putBucketLifecycleConfiguration([
        'Bucket' => 'bucket-name',
        'LifecycleConfiguration' => [
            'Rules' => [
                [
                    'ID' => 'rule1',
                    'Status' => 'Enabled',
                    'Filter' => ['Prefix' => 'logs/'],
                    'Transitions' => [
                        ['Days' => 30, 'StorageClass' => 'GLACIER'],
                    ],
                ],
            ],
        ],
    ]);
    

5. Async Operations with Promises

use AsyncAws\Core\Promise\Promise;

$promise = $client->putObjectAsync([
    'Bucket' => 'bucket-name',
    'Key' => 'file.txt',
    'Body' => fopen('file.txt', 'r'),
]);

$promise->then(function ($result) {
    echo "Uploaded successfully!";
})->catch(function ($exception) {
    echo "Upload failed: " . $exception->getMessage();
});

Integration Tips

Laravel Integration

  1. Service Provider Setup:

    use AsyncAws\S3\S3Client;
    use Illuminate\Support\ServiceProvider;
    
    class S3ServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton(S3Client::class, function ($app) {
                return new S3Client([
                    'region' => config('aws.region'),
                    'credentials' => [
                        'key' => config('aws.key'),
                        'secret' => config('aws.secret'),
                    ],
                ]);
            });
        }
    }
    
  2. Facade for Convenience:

    // config/aws.php
    return [
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
    ];
    
    // app/Providers/AppServiceProvider.php
    use Illuminate\Support\Facades\Facade;
    
    class AppServiceProvider extends ServiceProvider
    {
        public function boot()
        {
            Facade::register('S3', function () {
                return app(S3Client::class);
            });
        }
    }
    
  3. Usage in Controllers:

    use Illuminate\Support\Facades\S3;
    
    public function upload()
    {
        $result = S3::putObject([
            'Bucket' => 'my-bucket',
            'Key' => 'uploaded-file.jpg',
            'Body' => fopen('file.jpg', 'r'),
        ]);
        return response()->json(['success' => true]);
    }
    

Error Handling

  • Catch Exceptions:
    try {
        $client->putObject([...]);
    } catch (\AsyncAws\Core\Exception\AwsException $e) {
        // Handle AWS-specific errors
        if ($e->getAwsErrorCode() === 'AccessDenied') {
            // Handle access denied
        }
    } catch (\RuntimeException $e) {
        // Handle runtime errors
    }
    

Pagination

  • List Objects with Pagination:
    $paginator = $client->getPaginator('listObjectsV2', [
        'Bucket' => 'bucket-name',
    ]);
    
    foreach ($paginator as $page) {
        foreach ($page->getContents() as $object) {
            echo $object->getKey();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Region Configuration:

    • Ensure the region is correctly set, especially for directory buckets or regional endpoints. Some regions (e.g., us-east-1) do not require a LocationConstraint.
    • Example for us-west-2:
      $client = new S3Client([
          'region' => 'us-west-2',
          'endpoint' => 's3.us-west-2.amazonaws.com',
      ]);
      
  2. Path vs. Virtual Hosted-Style Endpoints:

    • By default, the client uses virtual hosted-style endpoints (e.g., https://bucket-name.s3.amazonaws.com).
    • To use path-style endpoints (e.g., https://s3.amazonaws.com/bucket-name), set:
      $client = new S3Client([
          's3PathStyleEndpoint' => true,
      ]);
      
  3. Bucket Naming:

    • Bucket names must be globally unique across all AWS accounts.
    • Avoid names starting with numbers or special characters (e.g., #, ?).
  4. Metadata Handling:

    • When uploading objects, metadata keys must be lowercase and prefixed with x-amz-meta-:
      $client->putObject([
          'Bucket' => 'bucket-name',
          'Key' => 'file.txt',
          'Metadata' => [
              'x-amz-meta-custom-key' => 'value', // Correct
              'CustomKey' => 'value', // Incorrect (will be prefixed internally)
          ],
      ]);
      
  5. Checksum Algorithms:

    • New checksum algorithms (e.g., CRC64, SHA-512) are supported but require explicit configuration:
      $client->putObject([
          'Bucket' => 'bucket-name',
          'Key' => 'file.txt',
          'Body' => fopen('file.txt', 'r'),
          'ChecksumAlgorithm' => 'CRC64', // Optional
      ]);
      
  6. Async Operations:

    • Async operations return a Promise; ensure you handle them properly:
      $promise = $client->putObjectAsync([...]);
      $result = $promise->wait(); // Blocks until completion
      // OR
      
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