How to Upload Files to Amazon S3 in Laravel 11?

By Hardik Savani September 4, 2024 Category : Laravel

In this article, i will show you step by step how to upload files and images in amazon s3 bucket storage with laravel 11.

What is AWS S3?

Amazon S3 (Simple Storage Service) is a cloud service that lets you store and manage your data online. Think of it as a huge, secure, and flexible online storage locker where you can keep files like photos, videos, and documents. It’s great because you can access your files from anywhere, only pay for what you use, and it scales with your needs.

In this example, we will use the composer package `league/flysystem-aws-s3-v3` to upload files to an Amazon S3 bucket. We will make a simple form for users to pick and upload a file. We will use Laravel’s filesystem to save the file to the S3 bucket. Let’s follow these steps:

laravel 11 s3 bucket storage

Step for Laravel 11 Amazon S3 File Upload Example

  • Step 1: Create S3 Bucket
  • Step 2: Install Laravel 11
  • Step 3: Install Amazon S3 Composer Package
  • Step 4: Configure AWS S3 Credentials
  • Step 5: Create Routes
  • Step 6: Create ImageUploadController
  • Step 7: Create Blade File
  • Run Laravel App

Step 1: Create S3 Bucket

First you need to create bucket and user so let's follow bellow step:

1. Go to Amazon Web Service Console and Login.

2. Click on S3 from Service Lists

3. Click on "Create Bucket" button and you will found bellow forms. you can enter your bucket name there.

4. Create Create IAM User. Click here to create IAM User.

5. Click on "Create User" button as bellow show you.

6. Next Add User Name and select "Programmatic access" from access type. then click on next.

7. Next Select “Attach Existing Policy Directly” and choose "AmazonS3FullAccess" from permission link.

8. It's optional so you can skip and click to next.

9. You can view user details and then click on "Create User" button.

10. Now you will see created user in link. there is a "Access Key ID" and "Secret Access Key" that we need on .env files.

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 3: Install Amazon S3 Composer Package

If you haven't installed the Amazon S3 package, you need to install the S3 Composer package with this command:

composer require league/flysystem-aws-s3-v3 "^3.0" --with-all-dependencies

Step 4: Configure AWS S3 Credentials

Add your AWS credentials to your `.env` file like this:

.env

AWS_ACCESS_KEY_ID=AKIAVAEWWDTDY...
AWS_SECRET_ACCESS_KEY=Zp/wgwj46SAC....
AWS_DEFAULT_REGION=us-east-2
AWS_BUCKET=itsolutionstuff-bucket
AWS_USE_PATH_STYLE_ENDPOINT=false

Step 5: Create Routes

Next, we'll add two new routes in the `web.php` file. One route will show a form, and the other will handle form submissions. Here’s how to create them:

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageUploadController;
  
Route::get('image-upload', [ ImageUploadController::class, 'imageUpload' ])->name('image.upload');
Route::post('image-upload', [ ImageUploadController::class, 'imageUploadPost' ])->name('image.upload.post');

Step 6: Create ImageUploadController

In the third step, we need to create a new ImageUploadController. In this, we will write two methods:

imageUpload(): This handles the GET request.

imageUploadPost(): This handles the POST request.

Now, let's add the code for these methods.

app/Http/Controllers/ImageUploadController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class ImageUploadController extends Controller
{
     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function imageUpload()
    {
        return view('imageUpload');
    }
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function imageUploadPost(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
    
        $imageName = time().'.'.$request->image->extension();  
     
        $path = Storage::disk('s3')->put('images', $request->image);
        $path = Storage::disk('s3')->url($path);
  
        /* Store $imageName name in DATABASE from HERE */
    
        return back()
            ->with('success','You have successfully upload image.')
            ->with('image', $path); 
    }
}

Step 7: Create Blade File

Finally, we need to make a file named imageUpload.blade.php. In this file, we will make a form with a button to upload a file. Copy the code below and put it in that file.

resources/views/imageUpload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel File Uploading with Amazon S3 - ItSolutionStuff.com.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
    
<body>
<div class="container">
     
    <div class="panel panel-primary">
      <div class="panel-heading"><h2>Laravel File Uploading with Amazon S3 - ItSolutionStuff.com.com</h2></div>
      <div class="panel-body">
     
        @if ($message = Session::get('success'))
        <div class="alert alert-success alert-block">
            <button type="button" class="close" data-dismiss="alert">×</button>
                <strong>{{ $message }}</strong>
        </div>
        <img src="{{ Session::get('image') }}">
        @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('image.upload.post') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="row">
    
                <div class="col-md-6">
                    <input type="file" name="image" 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>

Now you can run and check it.

Now we are ready to run our example. so run bellow command so quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/image-upload

Output:

S3 Uploaded Image:

I hope it can help you...

Shares