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

aws/aws-sdk-php-laravel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require aws/aws-sdk-php-laravel
    

    This auto-registers the AwsServiceProvider and publishes a config file at config/aws.php.

  2. Configure credentials: Edit config/aws.php and set your AWS credentials (preferably via environment variables):

    'credentials' => [
        'key'    => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'token'  => env('AWS_SESSION_TOKEN'), // Optional for temporary credentials
    ],
    

    Add these to your .env:

    AWS_ACCESS_KEY_ID=your-access-key
    AWS_SECRET_ACCESS_KEY=your-secret-key
    AWS_DEFAULT_REGION=us-east-1
    
  3. First AWS call: Use the facade or container to interact with AWS services:

    use Aws\S3\S3Client;
    use Aws\S3\Exception\S3Exception;
    
    try {
        $s3 = app('aws')->createClient('s3');
        $objects = $s3->listObjects(['Bucket' => 'your-bucket']);
        dd($objects);
    } catch (S3Exception $e) {
        dd($e->getMessage());
    }
    

Key Starting Points

  • Facade: app('aws') or Aws::client() (if using the facade alias).
  • Service Configuration: config/aws.php for region, version, and retry settings.
  • Environment Variables: Prefer .env for credentials (never hardcode).

Implementation Patterns

Common Workflows

  1. Service Client Initialization:

    // Reusable client (cached by Laravel container)
    $s3 = app('aws')->createClient('s3', [
        'version' => 'latest',
        'region'  => 'eu-west-1',
        'endpoint' => env('AWS_S3_ENDPOINT'), // For S3-compatible services
    ]);
    
  2. Dependency Injection: Bind the AWS client to a service class:

    use Illuminate\Support\Facades\App;
    
    class S3Uploader {
        protected $s3;
    
        public function __construct() {
            $this->s3 = App::make('aws')->createClient('s3');
        }
    
        public function upload($file, $bucket) {
            return $this->s3->putObject([
                'Bucket' => $bucket,
                'Key'    => 'path/to/file',
                'Body'   => fopen($file, 'r'),
            ]);
        }
    }
    
  3. Dynamic Service Selection: Use a helper method to avoid repetition:

    // In a service class
    protected function awsClient(string $service): mixed {
        return app('aws')->createClient($service);
    }
    
    // Usage
    $dynamo = $this->awsClient('dynamodb');
    
  4. Streaming Large Files: For S3 uploads/downloads, use streams to avoid memory issues:

    $s3->putObject([
        'Bucket' => 'bucket',
        'Key'    => 'large-file.zip',
        'Body'   => fopen('local-file.zip', 'r'),
    ]);
    
  5. Async Operations: Use Laravel queues to offload AWS tasks:

    use Illuminate\Support\Facades\Queue;
    
    Queue::push(function () {
        $sqs = app('aws')->createClient('sqs');
        $sqs->sendMessage([
            'QueueUrl' => 'your-queue-url',
            'MessageBody' => 'Hello AWS!',
        ]);
    });
    

Integration Tips

  • Laravel Filesystem: Integrate with Storage::disk('s3') for seamless S3 file handling.
  • Events: Dispatch Laravel events after AWS operations (e.g., FileUploaded).
  • Middleware: Validate AWS responses or transform data before returning to the user.
  • Testing: Use AWS_MOCK environment variable or Mockery to stub AWS clients:
    $mock = Mockery::mock('overload:Aws\S3\S3Client');
    $mock->shouldReceive('listObjects')->andReturn(['Contents' => []]);
    

Gotchas and Tips

Common Pitfalls

  1. Credential Overrides:

    • The package respects AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY but ignores AWS_CONFIG_FILE or ~/.aws/credentials. Always set credentials via .env.
    • Fix: Explicitly configure credentials in config/aws.php if using non-standard sources.
  2. Region Mismatches:

    • AWS services default to us-east-1 if no region is set. Always specify the region in the client config or .env.
    • Fix: Add 'region' => env('AWS_DEFAULT_REGION') to your client config.
  3. Caching Issues:

    • The Laravel container caches AWS clients. If you update credentials or regions dynamically, clear the cache:
      app('aws')->forgetInstances();
      
    • Tip: Use a singleton pattern for clients that don’t change (e.g., S3), but recreate clients for dynamic services (e.g., per-user SQS queues).
  4. Endpoint Overrides:

    • For S3-compatible services (e.g., DigitalOcean Spaces), set the endpoint but exclude https://:
      'endpoint' => env('AWS_S3_ENDPOINT', 's3.amazonaws.com') // No 'https://'
      
    • Gotcha: Including https:// will cause InvalidEndpointException.
  5. Version Conflicts:

    • The package pins aws/aws-sdk-php:^3.338.0. Avoid manually requiring newer versions unless necessary.
    • Fix: Use composer why-not aws/aws-sdk-php:^3.x to check compatibility.
  6. Retry Configurations:

    • The SDK’s retry logic may conflict with Laravel’s HTTP client. Disable retries for idempotent operations:
      $client = app('aws')->createClient('s3', [
          'retry_attempts' => 0,
      ]);
      

Debugging Tips

  • Enable Debugging: Add this to config/aws.php to log AWS requests:

    'debug' => env('AWS_DEBUG', false),
    

    Check logs at storage/logs/laravel.log for AWS API calls.

  • Validate Responses: Use json_encode($response, JSON_PRETTY_PRINT) to inspect complex responses (e.g., DynamoDB items).

  • Common Exceptions:

    • Aws\S3\Exception\S3Exception: Check bucket permissions or CORS settings.
    • Aws\Credentials\CredentialsException: Invalid or missing credentials.
    • Aws\Exception\InvalidEndpointException: Verify endpoint and region.

Extension Points

  1. Custom Credential Providers: Extend the provider to support custom credential sources (e.g., IAM roles):

    // In a service provider
    $this->app->singleton('aws.credentials', function () {
        return new CustomCredentialProvider();
    });
    
  2. Service-Specific Helpers: Create facade methods for common operations:

    // In a facade class
    public static function uploadToS3($file, $bucket, $key) {
        return static::client('s3')->putObject([
            'Bucket' => $bucket,
            'Key'    => $key,
            'Body'   => fopen($file, 'r'),
        ]);
    }
    
  3. Middleware for AWS: Add middleware to validate AWS responses or transform data:

    $kernel->pushMiddlewareToGroup('web', \App\Http\Middleware\ValidateAwsResponse::class);
    
  4. Dynamic Service Clients: Use a trait to dynamically create clients based on a service name:

    trait UsesAwsServices {
        protected function aws($service, array $config = []) {
            return app('aws')->createClient($service, $config);
        }
    }
    
  5. Testing: Stub AWS services in tests using Mockery or the aws/aws-sdk-php mocking utilities:

    $mockHandler = new Aws\Tests\MockHandler();
    $mockHandler->expect('S3->listObjects')->andReturn(['Contents' => []]);
    $client = new Aws\S3\S3Client([], ['handler' => $mockHandler]);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui