Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 67 ยท Validation, Sessions and Files

File Uploads and the Storage System

Handle file uploads in Laravel with validation, store files on local, public or S3 disks with the Storage facade, link public files and serve downloads safely.

Profile photos, invoices, CSV imports: almost every real application accepts files. Doing it well means validating what arrives, storing it somewhere sensible, giving it a name you control, and serving it back without opening a security hole. Laravel handles all four with one idea: the filesystem disk.

A disk is a named storage location, such as the private local disk, the web-visible public disk or an Amazon S3 bucket. Your code calls the same methods on every disk (put, get, delete, url), so moving uploads from your laptop to the cloud is a configuration change, not a rewrite. The plain-PHP version of this story is in file uploads; here you will see what the framework adds.

Receiving an uploaded file

An upload arrives as a multipart form. Your HTML form needs enctype="multipart/form-data" and the controller reads the file from the request (see requests and responses):

BLADE
<form method="POST" action="/avatar" enctype="multipart/form-data">
    @csrf
    <input type="file" name="avatar">
    <button>Upload</button>
</form>
PHP
use Illuminate\Http\Request;

Route::post('/avatar', function (Request $request) {
    $request->validate([
        'avatar' => ['required', 'image', 'max:2048'], // kilobytes
    ]);

    $path = $request->file('avatar')->store('avatars', 'public');

    return back()->with('status', "Saved to {$path}");
});

$request->file('avatar') returns an UploadedFile, a Symfony class with a few helpers: getClientOriginalName(), getSize(), extension() (guessed from the real content) and hashName(). $request->hasFile('avatar') checks that a file was sent and is valid.

store('avatars', 'public') saves the file in the avatars folder of the public disk under a generated unique name and returns the path, such as avatars/Vq3k...Zw.jpg. Store that path in your database, not a full URL. If you need to choose the name yourself, use storeAs('avatars', "user-{$id}.jpg", 'public'), and never build a name from the client's file name without cleaning it.

Validating files

Validation rules for uploads live in the same validate() call as everything else (see validation):

Rule Meaning
file The value is a successfully uploaded file
image The content is an image (JPEG, PNG, GIF, WebP and similar)
mimes:pdf,docx The extension that matches the detected MIME type is in the list
mimetypes:video/mp4 The detected MIME type is in the list
max:2048 At most 2048 kilobytes
dimensions:min_width=200,max_height=800 Image size limits

Note that mimes and image check the file's content, not the name the browser claims, which is exactly what you want. A file named photo.jpg that contains a script fails image. Also check PHP's own limits, upload_max_filesize and post_max_size; if a file exceeds them, PHP drops it before Laravel sees it and validation reports the field as failed.

The stand-in below validates a pretend upload the same way: it looks at the first bytes of the content (the "magic number") instead of trusting the file name, and enforces a size limit in kilobytes.

PHP Validating content, not the file name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Disks and configuration

Disks are defined in config/filesystems.php. The default disk comes from FILESYSTEM_DISK in .env:

PHP
'default' => env('FILESYSTEM_DISK', 'local'),

'disks' => [
    'local' => [
        'driver' => 'local',
        'root' => storage_path('app/private'),
    ],
    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
    ],
],

Two disks matter on day one:

  • local keeps files outside the web root, so nobody can request them by URL. Use it for invoices, exports and anything private. You serve them through a controller that checks permissions.
  • public is meant for files the whole world may see, such as avatars. Its folder, storage/app/public, is not inside public/ yet. Run the link command once per environment:
Terminal
php artisan storage:link

This creates the symlink public/storage pointing at storage/app/public. After that, Storage::disk('public')->url('avatars/x.jpg') produces a working /storage/avatars/x.jpg address. The link is not committed to Git, so repeat the command after a fresh clone or deployment.

flowchart LR
    C["Your code<br/>Storage::disk('name')"] --> D{"Which disk?"}
    D -->|local| L["storage/app/private<br/>not web-visible"]
    D -->|public| P["storage/app/public<br/>linked to public/storage"]
    D -->|s3| S["Cloud bucket"]

The same calls work on every disk; configuration decides where the bytes go.

The Storage facade

For files that do not come from a form, use the Storage facade (what a facade is: service providers and facades). Without disk() it uses the default disk:

PHP
use Illuminate\Support\Facades\Storage;

Storage::put('reports/2026-q1.csv', $csv);          // write
$csv = Storage::get('reports/2026-q1.csv');         // read
Storage::exists('reports/2026-q1.csv');             // true / false
Storage::append('logs/import.log', 'done');         // add a line
Storage::copy('a.txt', 'archive/a.txt');
Storage::move('a.txt', 'b.txt');
Storage::delete('b.txt');
Storage::size('archive/a.txt');                     // bytes
Storage::files('reports');                          // files in one folder
Storage::allFiles('reports');                       // recursive
Storage::makeDirectory('exports');
Storage::deleteDirectory('exports');

Storage::disk('public')->put('logo.svg', $svg);
Storage::disk('s3')->url('logo.svg');

Paths are always relative to the disk's root and use forward slashes. A path that tries to escape the root, such as ../../.env, is rejected by the underlying Flysystem library, but you should still never pass user-supplied paths straight through.

Here is a small stand-in for the idea: an in-memory filesystem with named disks, a store() that generates the file name, and a facade-like manager.

PHP An in-memory filesystem with disks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The real local disk behaves like the private one here: there is no public URL because the web server cannot reach the folder. That is a feature.

Serving files back

Public-disk files are served directly by the web server through the symlink. Private files need a route that decides who may see them:

PHP
Route::get('/invoices/{invoice}', function (Invoice $invoice) {
    Gate::authorize('view', $invoice);

    return Storage::download($invoice->path, "invoice-{$invoice->number}.pdf");
});

Storage::download() forces a download with the name you give it. Storage::response($path) streams the file inline, which is handy for images and PDFs shown in the browser. For S3 you can also create a temporary URL with Storage::temporaryUrl($path, now()->addMinutes(10)), a signed link that stops working after the time you set, so the file never needs to be public. The authorization side is covered in gates and policies.

Moving to S3

To use Amazon S3 (or any S3-compatible service), install the Flysystem adapter with Composer, fill in the AWS_* values in .env, and set FILESYSTEM_DISK=s3 or pass 's3' to store() and disk():

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

No controller code changes. Remember that uploads still pass through your server first; for very large files, browsers can also upload straight to the bucket with a temporary URL, which is a separate technique.

Safe-upload habits

  • Validate type and size on the server. Client-side checks are only a convenience.
  • Let Laravel generate the stored name. User-chosen names invite overwrites and odd characters; keep the original name in a database column if you need to show it.
  • Do not store uploads inside public/ unless everyone may read them, and never execute them. Serving user content from a separate domain or bucket is safer still.
  • Treat files that browsers render as active content (HTML, SVG) with extra care, since they can carry scripts.
  • In tests, call Storage::fake('public') and UploadedFile::fake()->image('a.jpg') so no real files are written (see faking and mocking).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $request->file('avatar')->store('avatars', 'public') return?

    store() generates a unique file name, saves the file on the given disk and returns its path. You keep that path in the database and turn it into a URL when needed.
  2. 2. Why do you run php artisan storage:link?

    The public disk keeps files outside the web root. The command creates a symbolic link inside public/ so the web server can serve them.
  3. 3. An invoice PDF must only be visible to its owner. Where should it be stored and how served?

    Private disks are not reachable by URL, so the only way in is your controller, where you can check permissions first.
  4. 4. Which validation rule checks the real content of an upload rather than the name the browser sends?

    The image (and mimes) rules inspect the file contents to detect its type, so renaming a script to photo.jpg does not pass.

Summary

  • Uploads reach the controller as UploadedFile; use $request->file(), hasFile() and store() or storeAs() (which return the stored path).
  • Validate with file, image, mimes, mimetypes, max (in kilobytes) and dimensions, and remember PHP's own size limits.
  • Disks in config/filesystems.php decide where files go: local is private, public is web-visible after php artisan storage:link, s3 is the cloud.
  • The Storage facade offers put, get, exists, delete, copy, move, files, url, download, response and temporaryUrl on any disk.
  • Serve private files through authorized routes; let Laravel generate stored names; never trust client file names or types.
  • Switching to S3 is an adapter package plus environment values, not a code rewrite.

Next: Database Configuration and the Query Builder