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

Aws Sdk Php Laravel Package

aws/aws-sdk-php

AWS SDK for PHP v3 provides PHP 8.1+ clients for Amazon Web Services like S3, DynamoDB, Glacier, and more. Install via Composer and use the included service APIs to authenticate, send requests, and build robust AWS-powered applications.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps for Laravel Integration
1. **Install the SDK**
   ```bash
   composer require aws/aws-sdk-php

Laravel developers often pair this with the official AWS SDK Laravel package for seamless integration with Laravel's service container.

  1. Configure AWS Credentials Store credentials in .env (recommended) or config/aws.php:

    AWS_ACCESS_KEY_ID=your_key
    AWS_SECRET_ACCESS_KEY=your_secret
    AWS_DEFAULT_REGION=us-west-2
    

    Use Laravel's config('services.aws') to access these values.

  2. First Use Case: Upload to S3

    use Aws\S3\S3Client;
    use Illuminate\Support\Facades\Storage;
    
    $s3 = new S3Client(config('services.aws'));
    $s3->putObject([
        'Bucket' => 'my-bucket',
        'Key'    => 'file.txt',
        'Body'   => Storage::disk('local')->get('file.txt'),
        'ACL'    => 'public-read',
    ]);
    

Where to Look First


Implementation Patterns

1. Service Client Initialization

Leverage Laravel's service container to bind the SDK client:

// config/app.php
'providers' => [
    Aws\Sdk\Laravel\AwsServiceProvider::class,
],

Access clients via:

$s3 = app('aws')->createS3();
$dynamodb = app('aws')->createDynamoDb();

2. Common Workflows

File Handling with S3 Stream Wrapper

Enable the S3 stream wrapper in config/filesystems.php:

'disks' => [
    's3' => [
        'driver' => 's3',
        'key'    => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'bucket' => env('AWS_BUCKET'),
        'region' => env('AWS_REGION'),
        'url'    => env('AWS_URL'),
    ],
],

Now use PHP's native file functions:

file_put_contents('s3://my-bucket/file.txt', 'Hello, S3!');

Pagination and Waiters

Use paginators for large datasets (e.g., S3 list objects):

$objects = $s3->getPaginator('listObjects', [
    'Bucket' => 'my-bucket',
]);
foreach ($objects as $page) {
    foreach ($page['Contents'] as $object) {
        // Process each object
    }
}

Use waiters for async operations (e.g., DynamoDB table creation):

$waiter = $dynamodb->getWaiter('tableExists');
$waiter->wait(['TableName' => 'my-table']);

Middleware for Request/Response Logging

Add Guzzle middleware for debugging:

$s3 = new S3Client([
    'region' => 'us-west-2',
    'http' => [
        'middleware' => [
            new Aws\Guzzle\Middleware::tap(function ($request) {
                Laravel\Log::debug('S3 Request:', $request->toPsr7());
            }),
        ],
    ],
]);

3. Integration with Laravel Jobs/Queues

Offload heavy AWS operations to queues:

use Aws\S3\S3Client;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;

class UploadToS3 implements ShouldQueue
{
    use Queueable;

    public function handle(S3Client $s3)
    {
        $s3->putObject([/* ... */]);
    }
}

4. Dynamic Credential Handling

Use IAM roles (for EC2) or temporary credentials (via Aws\Credentials\Credentials):

$client = new S3Client([
    'credentials' => Aws\Credentials\Credentials::fromCredentialsProvider(
        new Aws\Credentials\TemporaryCredentialsProvider([
            'key' => 'ASIA...',
            'secret' => '...',
            'token' => '...',
        ])
    ),
]);

Gotchas and Tips

Pitfalls

  1. Credential Leaks

    • Never hardcode credentials in code. Use Laravel's .env or AWS IAM roles.
    • Avoid committing .aws/credentials or config/aws.php to version control.
  2. Region Mismatches

    • Ensure the region in your client matches the AWS service's region. Example:
      $client = new S3Client(['region' => 'eu-central-1']); // Not us-west-2!
      
  3. Rate Limiting

    • AWS services throttle requests. Implement exponential backoff:
      $client = new S3Client([
          'http' => [
              'retry' => [
                  'max_attempts' => 5,
                  'delay' => 200, // ms
              ],
          ],
      ]);
      
  4. Stream Wrapper Quirks

    • The S3 stream wrapper (s3://) may not support all PHP file functions (e.g., file_get_contents for large files). Use the SDK's getObject instead:
      $result = $s3->getObject(['Bucket' => 'my-bucket', 'Key' => 'large-file.zip']);
      file_put_contents('local-file.zip', $result['Body']);
      
  5. DynamoDB Session Handler

    • The DynamoDbSessionHandler requires a DynamoDB table with a specific schema. Migrate existing sessions manually if switching from file-based storage.

Debugging Tips

  1. Enable Wire Logging Add this to your client config to log raw HTTP requests/responses:

    $client = new S3Client([
        'debug' => true,
        'http' => [
            'stream' => fopen('php://temp', 'w+'),
        ],
    ]);
    
  2. Validate IAM Permissions Use the AWS CLI to test permissions before coding:

    aws s3 ls s3://my-bucket --profile my-profile
    
  3. Check for Deprecated Methods The SDK evolves rapidly. Use php artisan ide-helper:generate to auto-complete and catch deprecations.

Extension Points

  1. Custom Middleware Extend Guzzle middleware for pre/post-processing:

    $client = new S3Client([
        'http' => [
            'middleware' => [
                new class implements Aws\Guzzle\Middleware {
                    public function __invoke($request, $handler) {
                        // Modify request
                        return $handler($request);
                    }
                },
            ],
        ],
    ]);
    
  2. Service-Specific Helpers Create Laravel helpers for common operations:

    // app/Services/S3Service.php
    class S3Service {
        public function __construct(private S3Client $s3) {}
    
        public function uploadFromLocal(string $path, string $bucket, string $key) {
            return $this->s3->putObject([
                'Bucket' => $bucket,
                'Key' => $key,
                'Body' => fopen($path, 'r'),
            ]);
        }
    }
    
  3. Event Listeners for AWS Events Use the SDK's event system to react to service changes:

    $client = new S3Client([
        'events' => [
            'aws.s3.*' => function ($event) {
                Log::info('S3 Event:', $event->getName());
            },
        ],
    ]);
    

Performance Tips

  1. Reuse Clients Instantiate clients once (e.g., in Laravel's service container) and reuse them:

    // config/app.php
    'bindings' => [
        S3Client::class => function () {
            return new S3Client(config('services.aws'));
        },
    ];
    
  2. Parallel Requests Use Guzzle's Promise for concurrent operations:

    $promises = [];
    foreach ($keys as $key) {
        $promises[] = $s3->getObject(['Bucket' => 'my-bucket', 'Key' => $key]);
    }
    $results = Aws\Guzzle\Promise\PromiseUtils::wait($promises);
    
  3. Transfer Acceleration Enable S3 transfer acceleration for faster uploads/downloads:

    $s3 = new S3Client([
        'endpoint' => 'my-bucket.s3-accelerate.amazonaws.com',
    ]);
    

Security Best Practices

  1. Least Privilege IAM Roles
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle