aws php sdk
package helps users to store or retrieve files on amazon aws s3 bucket in laravel applications.
Let’s start to get files or images from aws s3 cloud bucket server and display it:
Step 1: Install AWS SDK for PHP
To install AWS SDK for PHP using Composer command:
composer require aws/aws-sdk-php
Step 2: 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 3: 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 4: Create Get File Method
Create a method in controller file to handle get file or image logic in it:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class S3ImageController extends Controller
{
public function getImage($filename)
{
// Check if the file exists in the S3 bucket
if (Storage::disk('s3')->exists($filename)) {
// Get the file URL
$url = Storage::disk('s3')->url($filename);
// Optionally, you can return the file content
// $content = Storage::disk('s3')->get($filename);
// Return the URL or the content
return response()->json(['url' => $url]);
} else {
return response()->json(['error' => 'File not found.'], 404);
}
}
}
Step 5: Add Routes
Add route in routes/web.php
file that handle get file requests:
use App\Http\Controllers\S3ImageController;
Route::get('/image/{filename}', [S3ImageController::class, 'getImage']);
Step 6: Test Get File From S3 Bucket
Open the browser and test this application by typing /image/{filename}
route on browser.