Amazon S3 (Simple Storage Service) is the most popular cloud-based object storage service provided by Amazon Web Services (AWS).Amazon S3 is highly scalable, secure and durable data storage to store and retrieve data over the web.
Table Of Content
1 Prerequisites
1.) PHP version of 8.2
2.) Composer
3.) AWS Account
2 Introduction
Generally web applications stores, uploaded files in local web server. Alternatively you can store the files in any cloud storages, In this article, we're going to discuss how you can use Amazon S3 to store and manage files through Laravel 11 Application with the help of aws-sdk-php.
3 Install Laravel Project
First, make sure your computer has a composer.
Use the following command to install new Laravel Project.
You need to create or Login into AWS account
After Sign into the account, In the top bar and Search for the S3 service and go to the S3 Management Console.
In S3 Management Console create a New Bucket to store files.
Get AWS Access Key ID and AWS Secret Access Key:
Search "IAM Console" and go to the IAM Console.
From the left navigation menu, select Users under the Access management section.
Create a user with AmazonS3FullAccess permission.
Once User Created Succefully, the Access Key ID and Secret Access Key will be generated.
5 Install AWS SDK for PHP
First, make sure your computer has a composer.
Laravel already includes the Flysystem integration with AWS S3, so you just need to install the AWS SDK via Composer.
composer require league/flysystem-aws-s3-v3
6 Configure AWS Credentials in .env file
In the .env file, AWS configuration variables are defined.
Now create a controller "UploadController" and add index(),upload() and listFiles() methods
Use the following artisan command to Create Controller.
php artisan make:controller UploadController
app/Http/Controllers/UploadController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
class UploadController extends Controller
{
public function index()
{
return view('index');
}
public function upload(Request $request)
{
if ($request->hasFile('file'))
{
$file = $request->file('file');
$path = $file->store('uploads', 's3');
Storage::disk('s3')->setVisibility($path, 'private');
$url = Storage::disk('s3')->url($path);
return response()->json(['url' => $url]);
}
return response()->json(['error' => 'No file uploaded'], 400);
}
public function listFiles()
{
// List files in the root of the S3 bucket
$files = Storage::disk('s3')->files();
return view('list', compact('files'));
}
}
?>
9 Create Index Blade View File
Create View "index.blade.php" File to Show Form
resources/views/index.blade.php