How to use aws s3 async in laravel?

Member

by kadin , in category: PHP Frameworks , 5 months ago

How to use aws s3 async in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 5 months ago

@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. Install the AWS SDK for PHP by running the following command in your terminal:
1
composer require aws/aws-sdk-php


  1. Next, you will need to set up your AWS credentials. You can do this by adding your AWS access key ID, secret access key, and default region to your .env file:
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. Once you have set up your AWS credentials, you can start working with AWS S3 in your Laravel application. Here is an example of how you can upload a file to S3 asynchronously using Laravel's Queue functionality:
 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.