Laravel 11 Upload Files to Amazon S3 Example

18-Jun-2024

.

Admin

Laravel 11 Upload Files to Amazon S3 Example

Hi, Dev

In this article, I'll guide you through the process of uploading files and images to an Amazon S3 bucket using Laravel 11, step by step.

What is AWS S3?


Amazon S3 (Simple Storage Service) is a cloud-based solution for storing and managing your data online. Think of it as a massive, secure, and flexible online storage locker where you can keep various types of files, including photos, videos, and documents. It’s advantageous because you can access your files from anywhere, only pay for what you use, and scale storage according to 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'll create a simple form that allows users to select and upload a file. Using Laravel’s filesystem, we will save the file to the S3 bucket. Let’s follow these steps:

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.

laravel-11-create-bucket

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

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

laravel-11-create-user

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

laravel-11-programmatic-access

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

laravel11-permission-link

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

laravel-11-key-skip

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

laravel-11-create-user-amazon

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.

laravel-11-access -key-id-example

Step 2: 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 11 Upload Files to Amazon S3 Example - NiceSnippets.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 11 Upload Files to Amazon S3 Example - NiceSnippets.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:

laravel-11-output-amazon-img-upl

S3 Uploaded Image:

laravel-11-uploaded-image-example

I hope it can help you...

#Laravel 11