Amazon S3 (Simple Storage Service) bucket is a cloud storage that allows users to store data (files or folders) on a cloud server and retrieve the data from anywhere on the web using APIs.
Let’s start installing aws php sdk in laravel to upload file to cloud server:
Step 1: Set Up AWS S3 Bucket
- Log in to your AWS Console Management.
- Go to service => S3.
- Create a new S3 bucket.
- Save your AWS access key ID, secret access key, and the region where your bucket is located.
Step 2: Install AWS SDK for PHP
To install AWS SDK for PHP using Composer command:
composer require aws/aws-sdk-php
Step 3: Configure Laravel to Use S3
Configure S3 bucket in config/filesystems.php
file:
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
],
Step 4: Set Environment Variables
Define your AWS secrets and S3 bucket name to your .env
file:
AWS_ACCESS_KEY_ID=your-access-key-id
AWS_SECRET_ACCESS_KEY=your-secret-access-key
AWS_DEFAULT_REGION=your-region
AWS_BUCKET=your-bucket-name
AWS_URL=https://your-bucket-name.s3.amazonaws.com
Step 5: Create a Form for File Upload S3
Create a form in your view to allow users to upload files on aws s3 bucket:
<form action="{{ route('upload') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file">
<button type="submit">Upload File</button>
</form>
Step 6: Create File Upload Method
Create a method in controller file to handle the file upload and store it in S3:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
public function upload(Request $request)
{
$path = $request->file('file')->store('uploads', 's3');
// You can store additional data in your database or return a response as needed.
}
Step 7: Define Route
Define route in routes/web.php file that handle file upload request:
Route::post('/aws-upload', 'FileController@upload')->name('upload');
Step 8: Test File Upload
Open the browser and test this application by uploading a file from the form using /aws-upload
route.