@kadin
To use AWS S3 async in Laravel, you will need to install the AWS SDK for PHP via composer. Here are the steps to do this:
1
|
composer require aws/aws-sdk-php |
1 2 3 |
AWS_ACCESS_KEY_ID=your_access_key_id AWS_SECRET_ACCESS_KEY=your_secret_access_key AWS_DEFAULT_REGION=your_default_region |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
use AwsS3S3Client; use IlluminateSupportFacadesQueue; // Inside your controller or wherever you want to upload a file to S3 asynchronously $file = $request->file('file'); $fileName = $file->getClientOriginalName(); Queue::push(function ($job) use ($file, $fileName) { $s3 = new S3Client([ 'version' => 'latest', 'region' => env('AWS_DEFAULT_REGION'), 'credentials' => [ 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), ], ]); $s3->putObject([ 'Bucket' => 'your_bucket_name', 'Key' => 'path/to/' . $fileName, 'SourceFile' => $file->getPathname(), ]); $job->delete(); }); return response()->json(['message' => 'File uploaded to S3 asynchronously']); |
In the above example, we are using Laravel's Queue
facade to push a job onto the queue that uploads the file to S3 asynchronously. This way, the file upload will run in the background instead of blocking the request.
Remember to replace your_bucket_name
with your actual S3 bucket name and update the path where you want to upload the file on S3.