Install the package:
composer require aws/aws-sdk-php-laravel
This auto-registers the AwsServiceProvider and publishes a config file at config/aws.php.
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
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());
}
app('aws') or Aws::client() (if using the facade alias).config/aws.php for region, version, and retry settings..env for credentials (never hardcode).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
]);
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'),
]);
}
}
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');
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'),
]);
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!',
]);
});
Storage::disk('s3') for seamless S3 file handling.FileUploaded).AWS_MOCK environment variable or Mockery to stub AWS clients:
$mock = Mockery::mock('overload:Aws\S3\S3Client');
$mock->shouldReceive('listObjects')->andReturn(['Contents' => []]);
Credential Overrides:
AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY but ignores AWS_CONFIG_FILE or ~/.aws/credentials. Always set credentials via .env.config/aws.php if using non-standard sources.Region Mismatches:
us-east-1 if no region is set. Always specify the region in the client config or .env.'region' => env('AWS_DEFAULT_REGION') to your client config.Caching Issues:
app('aws')->forgetInstances();
Endpoint Overrides:
endpoint but exclude https://:
'endpoint' => env('AWS_S3_ENDPOINT', 's3.amazonaws.com') // No 'https://'
https:// will cause InvalidEndpointException.Version Conflicts:
aws/aws-sdk-php:^3.338.0. Avoid manually requiring newer versions unless necessary.composer why-not aws/aws-sdk-php:^3.x to check compatibility.Retry Configurations:
$client = app('aws')->createClient('s3', [
'retry_attempts' => 0,
]);
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.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();
});
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'),
]);
}
Middleware for AWS: Add middleware to validate AWS responses or transform data:
$kernel->pushMiddlewareToGroup('web', \App\Http\Middleware\ValidateAwsResponse::class);
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);
}
}
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]);
How can I help you explore Laravel packages today?