Amazon S3 (Simple Storage Service) provides cloud-based storage for saving and retrieving files and folders. Here’s how to set it up in Laravel 11 to handle file uploads using aws s3:
Integrating Amazon S3 with Laravel for File Storage
Amazon S3 (Simple Storage Service) provides cloud-based storage for saving and retrieving files and folders. Here’s how to set it up in Laravel to handle file uploads:
Step 1: Configure Your AWS S3 Bucket
- Log into the AWS Management Console.
- Navigate to the S3 service.
- Create a new S3 bucket.
- Make a note of your AWS access key ID, secret access key, and the region associated with your bucket.
Step 2: Install the AWS SDK for PHP
Use Composer to add the AWS SDK for PHP to your Laravel project:
composer require aws/aws-sdk-php
Step 3: Configure Laravel to Connect with S3
Edit the config/filesystems.php
file to include your S3 configuration:
'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
Update your .env
file with your AWS credentials and S3 bucket details:
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 File Upload Form
In your Blade view file, add a form to let users upload files to the S3 bucket:
<form action="{{ route('s3.upload') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
Step 6: Implement the File Upload Method
Define a method in your controller to handle the file upload and save it to S3:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
public function upload(Request $request)
{
$filePath = $request->file('file')->store('uploads', 's3');
// You can add additional logic here, such as saving the file path to the database.
}
Step 7: Set Up the Route
Add a route to routes/web.php
to manage the file upload requests:
Route::post('/s3-upload', [FileController::class, 'upload'])->name('s3.upload');
Step 8: Test the Upload Functionality
Launch your application and test the file upload feature by accessing the form through the /s3-upload
route in your browser.