PASSWORD RESET

Your destination for complete Tech news

How to upload files to Amazon s3 in Laravel?

392 0
< 1 min read

To upload files to Amazon S3 in Laravel, you can use the AWS SDK for PHP and the Laravel Storage facade.

Here are the steps to upload a file to Amazon S3 in Laravel:

Install the AWS SDK for PHP using Composer:

composer require aws/aws-sdk-php

Configure your AWS credentials in the config/services.php file or as environment variables. For example:

'aws' => [
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION'),
    'bucket' => env('AWS_BUCKET'),
],

Add a new disk in the config/filesystems.php file to use Amazon S3 as the storage provider:

's3' => [
    'driver' => 's3',
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION'),
    'bucket' => env('AWS_BUCKET'),
],

Use the Storage facade to upload the file to Amazon S3. For example:

use Illuminate\Support\Facades\Storage;

$path = Storage::disk('s3')->put('path/to/file', $file, 'public');

In this example, the put() method of the Storage facade is used to upload the file to the specified path in the S3 bucket. The third argument 'public' specifies that the file should be uploaded as a public file, which means that it can be accessed by anyone.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.