0
0
Laravelframework~5 mins

S3 cloud storage integration in Laravel

Choose your learning style9 modes available
Introduction

S3 cloud storage lets you save files safely on the internet instead of your computer. Laravel helps you connect to S3 easily to store and get files.

You want to save user-uploaded photos or documents online.
You need to share files across different servers or apps.
You want to keep backups of important files safely.
You want to serve files fast to users worldwide.
You want to avoid filling your local server storage.
Syntax
Laravel
use Illuminate\Support\Facades\Storage;

// Save a file to S3
Storage::disk('s3')->put('folder/filename.txt', 'File content');

// Get a file from S3
$content = Storage::disk('s3')->get('folder/filename.txt');

// Delete a file from S3
Storage::disk('s3')->delete('folder/filename.txt');

Use Storage::disk('s3') to work with S3 storage.

Make sure your S3 credentials are set in .env and config/filesystems.php.

Examples
Save a photo file to the 'photos' folder on S3.
Laravel
Storage::disk('s3')->put('photos/pic1.jpg', $fileContents);
Retrieve the contents of a PDF report from S3.
Laravel
$contents = Storage::disk('s3')->get('documents/report.pdf');
Remove an old file from S3 storage.
Laravel
Storage::disk('s3')->delete('old/file.txt');
Sample Program

This Laravel controller lets users upload files to S3 and download them back. It checks if the file exists before downloading.

Laravel
<?php

namespace App\Http\Controllers;

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

class FileController extends Controller
{
    public function upload(Request $request)
    {
        $request->validate([
            'file' => 'required|file',
        ]);

        $path = Storage::disk('s3')->putFile('uploads', $request->file('file'));

        return response()->json(['message' => 'File uploaded!', 'path' => $path]);
    }

    public function download($filename)
    {
        if (!Storage::disk('s3')->exists('uploads/' . $filename)) {
            return response()->json(['message' => 'File not found'], 404);
        }

        $file = Storage::disk('s3')->get('uploads/' . $filename);
        $type = Storage::disk('s3')->mimeType('uploads/' . $filename);

        return response($file, 200)->header('Content-Type', $type);
    }
}
OutputSuccess
Important Notes

Set your AWS keys in the .env file: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION, and AWS_BUCKET.

Run php artisan config:cache after changing config files to apply updates.

Use Laravel's built-in validation to check file types and sizes before uploading.

Summary

S3 integration in Laravel helps store files safely online.

Use Storage::disk('s3') to save, get, or delete files.

Always set AWS credentials and bucket info in your environment settings.