Laravel - How to upload file to AWS S3 Bucket


Uploading files to cloud storage is a common requirement in modern web applications. Amazon S3 (Simple Storage Service) is one of the most popular and reliable solutions for storing files in the cloud. By integrating Amazon S3 with your Laravel application, you can leverage S3's scalable and secure storage capabilities.

In this tutorial, we will walk you through the process of uploading files to Amazon S3 using Laravel. We will cover everything from setting up your Laravel project and configuring AWS credentials to creating a file upload form and handling file uploads in your application. By the end of this tutorial, you will have a fully functional Laravel application that can upload files to Amazon S3 and provide public access to those files.

Whether you are building a simple application that requires file uploads or a complex system that needs scalable storage solutions, this tutorial will give you the foundation you need to get started with file uploads to Amazon S3 in Laravel. Let’s dive in!

Step 1: Install Laravel

If you haven't already, install Laravel using Composer. Open your terminal and run:

composer create-project --prefer-dist laravel/laravel s3-upload-demo

Step 2: Install AWS SDK for PHP

Next, install the AWS SDK for PHP using Composer. In your terminal, navigate to your Laravel project directory and run:

composer require aws/aws-sdk-php

Step 3: Configure AWS S3 in Laravel

Create an S3 Bucket

  1. Log in to your AWS Management Console.
  2. Go to the S3 service.
  3. Click on "Create bucket".
  4. Follow the prompts to create a new S3 bucket.

Add AWS Credentials

Add your AWS credentials to your Laravel .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

Update your config/filesystems.php file to include the S3 disk configuration:


 

'disks' => [

    // other disks...

    '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'),
    ],

],

Step 4: Create a File Upload Form

Create a new controller for handling file uploads:

php artisan make:controller FileUploadController

In your FileUploadController.php, add the following methods:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FileUploadController extends Controller
{
    public function showUploadForm()
    {
        return view('upload');
    }

    public function uploadFile(Request $request)
    {
        $request->validate([
            'file' => 'required|file|mimes:jpg,png,pdf,docx|max:2048',
        ]);

        $file = $request->file('file');
        $path = $file->store('uploads', 's3');

        // Make the file publicly accessible
        Storage::disk('s3')->setVisibility($path, 'public');

        $url = Storage::disk('s3')->url($path);

        return back()->with('success', 'File uploaded successfully!')->with('file_url', $url);
    }
}

Create a new view file resources/views/upload.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Upload File to S3</title>
</head>
<body>
    <h1>Upload File to S3</h1>

    @if (session('success'))
        <div>
            <strong>{{ session('success') }}</strong>
        </div>
        <div>
            <a href="{{ session('file_url') }}">View Uploaded File</a>
        </div>
    @endif

    <form action="{{ route('upload.file') }}" method="post" enctype="multipart/form-data">
        @csrf
        <div>
            <label for="file">Choose file to upload</label>
            <input type="file" id="file" name="file">
        </div>
        <div>
            <button type="submit">Upload</button>
        </div>
    </form>
</body>
</html>

Step 5: Define Routes

Add the routes to handle the upload related requests routes/web.php:

use App\Http\Controllers\FileUploadController;

Route::get('/upload', [FileUploadController::class, 'showUploadForm'])->name('upload.form');
Route::post('/upload', [FileUploadController::class, 'uploadFile'])->name('upload.file');

Step 6: Run the Application

Start your Laravel development server:

php artisan serve

Visit http://127.0.0.1:8000/upload in your browser to see the file upload form. Select a file to upload, and you should see a success message with a link to view the uploaded file.

You have successfully created a Laravel application that uploads files to Amazon S3. This guide covered the basics, but you can expand upon this by adding more functionality, such as handling multiple file uploads or adding more file validation rules.


Recent Questions

Recent Tutorials
Laravel - How to upload file to AWS S3 Bucket

Explore how we can upload file using the laravel on Amazon S3 bucket.

How to Make an AWS S3 Bucket Public

Learn how we can make an AWS S3 bucket public

Laravel 10 - Tutorial on how to use jQuery to validate the form

Learn how to use jQuery in Laravel 10 to validate the form

Laravel 10 - Tutorial to create CRUD Application

Learn to create crud application using laravel 10. Step by step guidance will help to understand the concept of crud.

Laravel 10 - Send mail using AWS SES

Learn to send Email using Laravel 10 with AWS SES service.