Backend

Laravel File Storage and Uploads

Mayur Dabhi
Mayur Dabhi
May 6, 2026
14 min read

The avatar upload works fine on your laptop. Then you deploy, and the images 404 because nobody ran storage:link. Or the app moves to two servers behind a load balancer, and half the uploads live on a disk the other server can't see. File handling looks simple until it isn't.

This post walks through how Laravel's filesystem layer (built on Flysystem) handles local and S3 storage, how to validate and store uploads safely, how to serve private files, and what to do about large files.

One API for Every Disk

Laravel wraps the Flysystem library, so local, S3 and SFTP disks all expose the same methods. In practice you can develop against the local disk and switch to S3 in production by changing an environment variable, as long as you always go through Storage and never build file paths by hand.

The Filesystem Architecture

Everything revolves around disks: named storage backends defined in config/filesystems.php. Each disk has a driver (local, s3, ftp, sftp) plus driver-specific options like a root path or bucket name.

A fresh Laravel app comes with three disks:

Laravel App Storage::disk('...') Flysystem local public s3 sftp HTTP Request Laravel Filesystem: One API, Many Backends

Laravel's Flysystem abstraction routes Storage calls to any backend disk

Configuration

All disks live in config/filesystems.php. Keep anything sensitive in .env and out of the config file, since that file ends up in git.

config/filesystems.php
'default' => env('FILESYSTEM_DISK', 'local'),

'disks' => [
    'local' => [
        'driver' => 'local',
        'root'   => storage_path('app'),
        'throw'  => false,
    ],

    'public' => [
        'driver'     => 'local',
        'root'       => storage_path('app/public'),
        'url'        => env('APP_URL').'/storage',
        'visibility' => 'public',
        'throw'      => false,
    ],

    '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'),  // for S3-compatible (e.g. R2)
        'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
        'throw'    => false,
    ],
],

Creating the Public Symlink

The public disk only becomes reachable from the browser once there's a symlink from public/storage to storage/app/public:

Terminal
php artisan storage:link
Deployment Reminder

Put php artisan storage:link in your deploy script, not just your memory. Zero-downtime tools that create a new release folder each time will lose the link otherwise. If you're using Docker or a shared hosting environment, make sure the web server can follow symlinks (check Options +FollowSymLinks in Apache or disable_symlinks off in Nginx).

Basic File Operations

You'll do almost everything through the Storage facade. Call Storage::disk('name') to pick a disk; skip it and you get the default disk from your config.

Basic Storage Operations
use Illuminate\Support\Facades\Storage;

// Write a file
Storage::put('reports/q1.pdf', $pdfContent);

// Write to a specific disk
Storage::disk('s3')->put('reports/q1.pdf', $pdfContent);

// Read a file
$content = Storage::get('reports/q1.pdf');

// Check existence
if (Storage::exists('reports/q1.pdf')) { ... }

// Get file size in bytes
$size = Storage::size('reports/q1.pdf');

// Get last modified timestamp
$timestamp = Storage::lastModified('reports/q1.pdf');

// Delete a file
Storage::delete('reports/q1.pdf');

// Delete multiple files
Storage::delete(['file1.txt', 'file2.txt']);

// List files in a directory
$files = Storage::files('reports');
$allFiles = Storage::allFiles('reports'); // recursive

// List directories
$dirs = Storage::directories('reports');

// Create a directory
Storage::makeDirectory('reports/2026');

// Delete a directory (and its contents)
Storage::deleteDirectory('reports/temp');

File Visibility

Files stored via the local driver are private by default. To make a file publicly accessible when using a cloud driver like S3, set its visibility to public:

File Visibility
// Store with explicit visibility
Storage::disk('s3')->put('avatars/user-1.jpg', $data, 'public');

// Change visibility after storing
Storage::setVisibility('avatars/user-1.jpg', 'public');

// Get current visibility
$visibility = Storage::getVisibility('avatars/user-1.jpg'); // 'public' or 'private'

// Get public URL (works for public disk and public S3 files)
$url = Storage::url('avatars/user-1.jpg');

// Generate a temporary signed URL for private files (S3 only)
$signedUrl = Storage::disk('s3')->temporaryUrl(
    'documents/contract.pdf',
    now()->addMinutes(30)
);

Handling HTTP File Uploads

Uploaded files arrive as Illuminate\Http\UploadedFile instances (a subclass of Symfony's UploadedFile). Two methods cover most cases: store and storeAs.

The store() Method

store() gives the file a random 40-character name and guesses the extension from the file's contents, so you don't have to worry about collisions or user-supplied names. It's what I reach for by default:

app/Http/Controllers/ProfileController.php
public function updateAvatar(Request $request)
{
    $request->validate([
        'avatar' => 'required|image|mimes:jpg,jpeg,png,gif,webp|max:2048',
    ]);

    $file = $request->file('avatar');

    // store() returns the generated path, e.g. "avatars/abc123def456.jpg"
    $path = $file->store('avatars', 'public');

    // Delete old avatar if exists
    if ($request->user()->avatar_path) {
        Storage::disk('public')->delete($request->user()->avatar_path);
    }

    $request->user()->update(['avatar_path' => $path]);

    return back()->with('success', 'Avatar updated successfully.');
}

The storeAs() Method

If you need control over the filename, say to include a user ID or a slug, use storeAs():

storeAs() with Custom Filename
public function uploadDocument(Request $request)
{
    $request->validate([
        'document' => 'required|file|mimes:pdf,doc,docx|max:10240',
    ]);

    $file     = $request->file('document');
    $ext      = $file->getClientOriginalExtension();
    $filename = 'contract-' . auth()->id() . '-' . time() . '.' . $ext;

    $path = $file->storeAs('documents', $filename, 's3');

    Document::create([
        'user_id'   => auth()->id(),
        'file_path' => $path,
        'file_name' => $file->getClientOriginalName(),
        'file_size' => $file->getSize(),
        'mime_type' => $file->getMimeType(),
    ]);

    return response()->json(['path' => $path], 201);
}

File Validation Best Practices

Treat the filename, extension and MIME type the browser sends as suggestions at best. Laravel's validation rules let you allow exactly what you expect and reject the rest. These are the ones I use most:

Rule What It Validates Example
file Is a successfully uploaded file 'doc' => 'file'
image JPEG, PNG, GIF, BMP, SVG, or WebP 'photo' => 'image'
mimes:jpg,png MIME type by content inspection 'photo' => 'mimes:jpg,png,webp'
mimetypes:image/jpeg Exact MIME type string 'photo' => 'mimetypes:image/jpeg'
max:2048 Maximum file size in kilobytes 'doc' => 'max:10240'
min:10 Minimum file size in kilobytes 'video' => 'min:100'
dimensions:... Image width/height constraints 'avatar' => 'dimensions:max_width=500,max_height=500'
extensions:pdf,docx File extension (Laravel 10.31+) 'report' => 'extensions:pdf,xlsx'
Security: MIME vs Extension

Always use mimes or mimetypes instead of relying on getClientOriginalExtension(). A malicious user can rename shell.php to shell.jpg. Laravel's mimes rule uses finfo_file() to inspect the actual binary content, making it much harder to spoof.

When max: Never Gets a Chance

Your max:10240 rule is irrelevant if PHP rejects the file first. A file larger than upload_max_filesize fails validation with the vague "The document failed to upload." message. A request bigger than post_max_size never reaches your rules at all: Laravel throws a PostTooLargeException (HTTP 413). And if Nginx's client_max_body_size (1 MB by default) is lower still, you get Nginx's own 413 page before PHP even runs. When uploads "randomly" fail in production, check those three limits first.

Multiple File Uploads

Handling Multiple Files
// HTML form
// <input type="file" name="photos[]" multiple>

// Validation
$request->validate([
    'photos'   => 'required|array|max:5',
    'photos.*' => 'image|mimes:jpg,jpeg,png,webp|max:4096',
]);

// Process each file
$paths = [];
foreach ($request->file('photos') as $photo) {
    $paths[] = $photo->store('gallery', 'public');
}

// Or using collect()
$paths = collect($request->file('photos'))
    ->map(fn ($file) => $file->store('gallery', 'public'))
    ->toArray();

Amazon S3 and Cloud Storage

Switching from local to S3 means installing the Flysystem S3 adapter and updating .env. If your code already goes through Storage, it doesn't need to change.

1

Install the AWS SDK

Laravel uses the league/flysystem-aws-s3-v3 package for S3 integration.

Terminal
composer require league/flysystem-aws-s3-v3 "^3.0"
2

Configure Environment Variables

Add your AWS credentials and bucket name to .env.

.env
FILESYSTEM_DISK=s3

AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=my-app-uploads
AWS_URL=https://my-app-uploads.s3.us-east-1.amazonaws.com
3

Use S3 in Your Code

Since FILESYSTEM_DISK=s3, Storage::put() now writes directly to S3. For multi-disk apps, explicitly specify the disk.

S3 Upload with Temporary URL
// Upload (same API as local)
$path = $request->file('invoice')->store('invoices', 's3');

// Get a permanent URL (only works if the file is public)
$url = Storage::disk('s3')->url($path);

// Get a 60-minute temporary signed URL for private files
$signedUrl = Storage::disk('s3')->temporaryUrl($path, now()->addHour());

// Stream a large file to avoid memory exhaustion
return response()->stream(function () use ($path) {
    $stream = Storage::disk('s3')->readStream($path);
    fpassthru($stream);
    fclose($stream);
}, 200, [
    'Content-Type'        => Storage::disk('s3')->mimeType($path),
    'Content-Disposition' => 'attachment; filename="'.basename($path).'"',
]);

DigitalOcean Spaces and Cloudflare R2

Both services are S3-compatible. The only difference is the endpoint and use_path_style_endpoint settings:

.env (DigitalOcean Spaces)
AWS_ACCESS_KEY_ID=DO_SPACES_KEY
AWS_SECRET_ACCESS_KEY=DO_SPACES_SECRET
AWS_DEFAULT_REGION=nyc3
AWS_BUCKET=my-spaces-bucket
AWS_ENDPOINT=https://nyc3.digitaloceanspaces.com
AWS_URL=https://my-spaces-bucket.nyc3.digitaloceanspaces.com
AWS_USE_PATH_STYLE_ENDPOINT=false

Image Processing with Intervention Image

Phones happily upload 8 MB photos for a 200px avatar. Resizing on the server before you store keeps that out of your bucket and your users' bandwidth. In Laravel, the usual package for this is Intervention Image v3.

Terminal
composer require intervention/image
Resize, Crop and Store
use Intervention\Image\Laravel\Facades\Image;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

public function uploadAvatar(Request $request)
{
    $request->validate([
        'avatar' => 'required|image|mimes:jpg,jpeg,png,webp|max:5120',
    ]);

    $file     = $request->file('avatar');
    $filename = Str::uuid() . '.jpg';

    // Resize to 200x200, cover crop, convert to JPEG
    $image = Image::read($file)
        ->cover(200, 200)
        ->toJpeg(quality: 85);

    // Store the processed image bytes
    Storage::disk('public')->put("avatars/{$filename}", (string) $image);

    // Optional: also create a thumbnail
    $thumb = Image::read($file)
        ->cover(50, 50)
        ->toJpeg(quality: 75);

    Storage::disk('public')->put("avatars/thumbs/{$filename}", (string) $thumb);

    $request->user()->update(['avatar' => "avatars/{$filename}"]);

    return back()->with('success', 'Avatar uploaded.');
}

Security Best Practices

An upload form lets strangers put files on your server, so it gets attacked a lot. This is the checklist I run through:

Complete Security Checklist

Threat Mitigation
PHP file execution via upload Never store uploads inside the public/ web root; use storage/app or S3
MIME spoofing Use mimes or mimetypes validation (inspects binary); never trust extension alone
Path traversal Never use client filenames directly; always generate your own using Str::uuid() or hash_file()
Oversize uploads (DoS) Enforce max: in validation AND set upload_max_filesize and post_max_size in php.ini
Sensitive file exposure Use temporary signed URLs for private files; never serve them via direct S3 URL
Server-side image attacks (ImageMagick) Use Intervention Image with GD driver; keep ImageMagick policy.xml hardened if used
SVG XSS Sanitize SVGs with a dedicated sanitizer such as enshrined/svg-sanitize, or reject SVGs from user uploads entirely

Serving Private Files Through Laravel

Contracts, invoices and anything else tied to a user shouldn't have a guessable URL. Send every request through a controller that checks permissions before touching the file:

routes/web.php + DocumentController.php
// routes/web.php
Route::get('/documents/{document}/download', [DocumentController::class, 'download'])
    ->middleware('auth')
    ->name('documents.download');

// app/Http/Controllers/DocumentController.php
public function download(Document $document)
{
    // Authorise: only the owner can download
    Gate::authorize('view', $document);

    // File stored privately on S3 (not public)
    $path = $document->file_path;

    if (!Storage::disk('s3')->exists($path)) {
        abort(404, 'File not found.');
    }

    return Storage::disk('s3')->download($path, $document->original_name);
}

// Or stream directly without temp files:
public function preview(Document $document)
{
    Gate::authorize('view', $document);

    return response()->stream(function () use ($document) {
        $stream = Storage::disk('s3')->readStream($document->file_path);
        fpassthru($stream);
    }, 200, [
        'Content-Type' => $document->mime_type,
        'Cache-Control' => 'private, max-age=3600',
    ]);
}

Chunked Uploads for Large Files

Sending a 2 GB video in one HTTP request is asking for trouble. Connections time out, you hit the size limits above, and a failed upload means starting from zero. Chunked uploads split the file in the browser and put it back together on the server.

ChunkedUploadController.php
public function uploadChunk(Request $request)
{
    $request->validate([
        'file'          => 'required|file|max:51200',  // 50MB per chunk
        'upload_id'     => 'required|uuid',
        'chunk_index'   => 'required|integer|min:0',
        'total_chunks'  => 'required|integer|min:1',
    ]);

    $uploadId    = $request->input('upload_id');
    $chunkIndex  = $request->input('chunk_index');
    $totalChunks = (int) $request->input('total_chunks');
    $chunk       = $request->file('file');

    // Store each chunk temporarily
    $chunk->storeAs("chunks/{$uploadId}", "part_{$chunkIndex}", 'local');

    // Check if all chunks have arrived
    $storedChunks = Storage::disk('local')->files("chunks/{$uploadId}");

    if (count($storedChunks) === $totalChunks) {
        // Reassemble
        $finalPath = "uploads/{$uploadId}.bin";
        $stream    = Storage::disk('local')->writeStream($finalPath, fopen('php://temp', 'r+'));

        for ($i = 0; $i < $totalChunks; $i++) {
            $chunkContent = Storage::disk('local')->get("chunks/{$uploadId}/part_{$i}");
            Storage::disk('s3')->append($finalPath, $chunkContent);
        }

        // Clean up temp chunks
        Storage::disk('local')->deleteDirectory("chunks/{$uploadId}");

        return response()->json(['status' => 'complete', 'path' => $finalPath]);
    }

    return response()->json(['status' => 'chunk_received', 'index' => $chunkIndex]);
}
Production Tip: Use a Dedicated Library

Treat the controller above as a sketch. One catch: S3 has no real append, so Storage::append() on an S3 disk downloads the whole object, adds the chunk and uploads it again. That gets slower with every chunk. For production, I'd use Filepond on the frontend with pion/laravel-chunk-upload on the backend, which deal with chunk ordering, retries and cleanup for you.

What to Check Before Going to Production

Most upload bugs I run into aren't in the controller. They're in the environment around it.

Pre-deploy Checklist

  • More than one server? Use S3 (or another shared disk), not the local or public disk. Local files only exist on the machine that received the upload.
  • New S3 bucket? Buckets created since 2023 have ACLs disabled by default, so passing 'public' visibility can fail with an AccessControlListNotSupported error. Either serve files with temporary URLs or make the bucket public with a bucket policy instead of per-object ACLs.
  • Size limits line up: Nginx client_max_body_size, PHP post_max_size and upload_max_filesize, and your max: rule should agree, or users get confusing errors.
  • Orphaned files: if you store the file and then the database insert fails, the file stays behind. Delete it in a catch, and schedule a job that clears out abandoned chunks/ folders.
  • Downloads through PHP: streaming via a controller ties up a PHP worker for the whole download. For big files, check permissions in the controller and then redirect to a short-lived temporaryUrl() instead.

When wouldn't I use all of this? For a small single-server app where users upload a handful of images, the public disk with store() and solid validation is plenty. I'd skip chunked uploads unless files regularly go past what your server limits allow, and skip image processing if you already put a CDN with on-the-fly resizing in front of storage. And if users upload very large files directly, generating a presigned upload URL so the browser sends the file straight to S3 is often simpler than proxying gigabytes through Laravel at all.

Laravel Files Storage S3 PHP Backend Security
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.