laravel save to s3
How to Save Laravel Files to Amazon S3
If you are planning to save your Laravel files to Amazon S3, it is important to set up your Amazon Web Services (AWS) account first. After that, follow the steps below:
Step 1: Install the Required Packages
Install the following packages using Composer:
composer require league/flysystem-aws-s3-v3 ^1.0
composer require aws/aws-sdk-php
Step 2: Configure Your AWS Credentials
In your Laravel project, create a new file named .env
if it doesn't exist yet. Add the following lines and replace the placeholders with your own AWS credentials:
AWS_ACCESS_KEY_ID=your_aws_access_key_id_here
AWS_SECRET_ACCESS_KEY=your_aws_secret_access_key_here
AWS_DEFAULT_REGION=your_aws_region_here
AWS_BUCKET=your_aws_bucket_name_here
Step 3: Set Up the Filesystem Configuration
In config/filesystems.php
, add the following code to the disks
array:
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
],
Step 4: Save a File to S3
To save a file to S3, you can use Laravel's Storage
facade. For example:
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
$file = new File('/path/to/local/file');
Storage::disk('s3')->put('path/to/s3/file', $file);
You can also use the putFile
method to save a file directly from a user input:
use Illuminate\Http\Request;
public function saveToS3(Request $request)
{
$file = $request->file('file');
Storage::disk('s3')->putFile('path/to/s3/file', $file);
return back();
}
Step 5: Retrieve a File from S3
To retrieve a file from S3, you can use the url
method to get a public URL for the file:
$url = Storage::disk('s3')->url('path/to/s3/file');
return view('download')->with('url', $url);
You can also use the get
method to retrieve the file contents:
$contents = Storage::disk('s3')->get('path/to/s3/file');
return response($contents)->header('Content-Type', 'application/pdf');