#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Uploading Files and Validating Uploads

File uploads — profile pictures, documents, attachments — are a common requirement in real applications, and Laravel provides a clean, consistent way to accept and validate them before anything gets saved.

Accepting a File Upload

A file input in an HTML form must include the enctype="multipart/form-data" attribute, or the file simply won't be sent. On the Laravel side, the uploaded file is accessible through the request object as an instance of Laravel's file class, which wraps helpful metadata like original name and size.

Validating Uploaded Files

Just like any other form input, uploaded files should be validated before being trusted or stored. Laravel includes several rules specifically for files, covering type, size, and even image dimensions.

RuleWhat It Checks
fileConfirms the input is a successfully uploaded file
imageRestricts the upload to common image formats
mimes:pdf,docxRestricts uploads to specific file extensions
max:2048Limits file size, specified in kilobytes
dimensions:min_width=100Enforces minimum or maximum image dimensions

Good Practices for Uploads

Once a file passes validation, it needs somewhere to actually live — which raises the question of where Laravel stores files, and the difference between its public and storage folders.

A Complete Upload Flow

Here is a minimal but realistic example: a user uploads a profile photo, and the app validates and stores it. Start with the form:

<form action="{{ route('avatar.update') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <input type="file" name="avatar" accept="image/*">
    @error('avatar') <p>{{ $message }}</p> @enderror
    <button type="submit">Upload</button>
</form>

Then the controller method:

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

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

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

    return back()->with('status', 'Photo updated');
}

What happens, step by step:

  1. The browser sends the file as multipart form data with the CSRF token.
  2. If validation fails, Laravel redirects back and the @error block shows the message.
  3. store() creates a random, unique filename and saves it in storage/app/public/avatars.
  4. Only the relative path is saved in the database, not the file itself.

Run php artisan storage:link once so files on the public disk can be reached through the public/storage link.

Richer Validation Options

The mimes rule checks the detected MIME type of the content, not just the extension the user typed, so a renamed executable will not pass as a PNG. Newer Laravel versions also offer a fluent rule object:

use Illuminate\Validation\Rules\File;

$request->validate([
    'report'   => ['required', File::types(['pdf', 'docx'])->max('5mb')],
    'photos'   => ['array', 'max:5'],
    'photos.*' => ['image', 'max:2048'],
]);

The photos.* key applies the rule to each file in a multi-file input named photos[].

Storing Private Files Safely

Not every upload should be public. Invoices, ID documents and contracts belong on a private disk, served through a controller that checks permission first:

$path = $request->file('invoice')->store('invoices');   // default private disk

public function download(Invoice $invoice)
{
    $this->authorize('view', $invoice);
    return Storage::download($invoice->file_path);
}

This way, guessing a URL never exposes another user's document.

A few more defensive habits are worth adopting. Do not build a storage path from the original client filename, since it can contain odd characters or path segments; use store() or hashName() instead. If you must show the original name, save it in a separate column and escape it when displaying. For public images, consider re-encoding or resizing them with an image library, which also strips unexpected embedded data. Finally, never place uploads in a folder where the web server would execute PHP files.

Upload Problems and How to Prevent Them

ProblemFix
$request->file() returns nullAdd enctype="multipart/form-data" to the form
Large files fail before validation runsRaise upload_max_filesize and post_max_size in PHP settings, and the web server's body size limit
Uploaded image shows a 404The storage link is missing or the wrong disk was used
Old files pile upDelete the previous file with Storage::disk('public')->delete($old) when replacing it

Checklist: multipart form, CSRF token, type and size rules, generated filenames, private disk for sensitive files, and authorization before downloads.

Ready to master Laravel Training Course?

Join Uncodemy's hands-on Laravel program and build real, production-ready applications.

Explore Course