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.

Laravel 11 AWS S3 - How to Use AWS S3 Bucket in Laravel 11 to Store and Manage files

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.

composer create-project laravel/laravel laravel-amazon-s3-app

Then, navigate to your project directory:

cd laravel-amazon-s3-app

4 Create / Login into AWS Account

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.

AWS_ACCESS_KEY_ID=xxxxxx
AWS_SECRET_ACCESS_KEY=xxxxxx
AWS_DEFAULT_REGION=xxxxxx
AWS_BUCKET=xxxxxx
AWS_URL=xxxxxx
AWS_ENDPOINT=xxxxxx
AWS_USE_PATH_STYLE_ENDPOINT=false

7 Configure the Filesystem

Update the config/filesystems.php file to configure the S3 driver:

'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'),
    'endpoint' => env('AWS_ENDPOINT'), // Optional: Add this if you're using a custom endpoint
    'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false), // Optional
],

8 Create New Controller - UploadController

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

<!DOCTYPE html>
<html>
<head>
    <title>Laravel File Storage with Amazon S3 </title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
</head>

<body>
<div class="container d-flex justify-content-center align-items-center" style="height: 100vh;">

    <div class="panel panel-primary">
      <div class="panel-heading"><h2>Laravel File Storage with Amazon S3 </h2></div>
      <div class="panel-body">

        @if (Session::get('message'))
        <div class="alert alert-success alert-block">
                <strong>{{Session::get('message')}}</strong>
        </div>
        @endif

        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <strong>Whoops!</strong> There were some problems with your input.
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <form action="{{ route('upload') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="row">
              

                <div class="col-md-6">
                    <label for="">Upload File</label>
                    <input type="file" name="file" class="form-control">
                </div>

                <div class="col-md-6">
                    <button type="submit" class="btn btn-success">Upload</button>
                </div>

            </div>
        </form>

      </div>
    </div>
</div>
</body>

</html>


10 Create List Blade View File

Create View "list.blade.php" File to Show Form resources/views/list.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel File Storage with Amazon S3 </title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
</head>

<body>
<div class="container d-flex justify-content-center align-items-center" style="height: 100vh;">

    <div class="panel panel-primary">
      <div class="panel-heading"><h2>Laravel File Storage with Amazon S3 </h2></div>
      <div class="panel-body">
      <table border="1px" class="table">
  <thead>
  <tr>
    <th>Filename</th>
  </tr>
</thead>
<tr>

@foreach($files as $row)
<tr>
  <td>
  {{$row}}
  </td>
 
</tr>
@endforeach
</table>
      </div>
    </div>
</div>
</body>

</html>


11 Define a Route

Define routes for the UploadController in the web.php file
routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UploadController;


Route::get('/', function () {
    return view('welcome');
});
Route::get('index', [ UploadController::class, 'index' ]);
Route::post('/upload', [UploadController::class, 'upload'])->name('upload');
Route::get('/s3-files', [UploadController::class, 'listFiles']);


12 Folder Structure

13 Run Laravel Server to Test the App

Use the following artisan command to Test the App.

php artisan serve

Visit the URL http://127.0.0.1:8000

14 Conclusion

That’s all we need to do. You can use this code in the web Applications to allow the user to upload files on Amazon Simple Storage Service (S3).

Tags