Laravel HTTP Requests: Input Handling, Validation & File Uploads

Every time a client submits a form, transmits a JSON payload, or uploads a file, Laravel encapsulates the raw PHP superglobals ($_GET, $_POST, $_FILES, $_SERVER) into an object-oriented Illuminate\Http\Request instance. In this class, you will master input retrieval, sanitization, inline validation, and secure file storage.

1. Accessing the Request via Dependency Injection

To obtain an instance of the current HTTP request within your controller action, simply type-hint the Illuminate\Http\Request class on your method. The Service Container automatically injects it:

use Illuminate\Http\Request;

public function store(Request $request)
{
    // Retrieve a single input field
    $email = $request->input('email');

    // With a default fallback if null
    $role = $request->input('role', 'subscriber');

    // Retrieve all input as an associative array
    $allData = $request->all();

    // Retrieve only specific keys (safe whitelist)
    $safeInput = $request->only(['username', 'email']);

    // Retrieve everything except sensitive fields
    $filtered = $request->except(['credit_card_cvv']);

    // Check if input is present
    if ($request->has('newsletter')) {
        // ...
    }
}

2. Inline Request Validation

Laravel provides an extensive array of over 90 built-in validation rules. When validation fails, Laravel automatically interrupts execution and redirects the user back to their previous page with error messages flashed into the session:

public function updateProfile(Request $request)
{
    $validated = $request->validate([
        'name'     => 'required|string|min:3|max:100',
        'email'    => 'required|email|unique:users,email,' . auth()->id(),
        'age'      => 'nullable|integer|between:18,99',
        'website'  => 'nullable|url',
    ]);

    // If validation succeeds, $validated contains ONLY the validated keys
    auth()->user()->update($validated);

    return back()->with('success', 'Profile updated successfully!');
}

3. Secure File Uploads & Storage Disk Management

Handling file uploads with raw PHP is notoriously dangerous due to directory traversal, malicious MIME spoofing, and file permissions. Laravel makes secure file storage effortless:

public function uploadAvatar(Request $request)
{
    // 1. Strict validation on uploaded file
    $request->validate([
        'avatar' => 'required|image|mimes:jpg,jpeg,png,webp|max:2048', // 2MB max
    ]);

    if ($request->hasFile('avatar') && $request->file('avatar')->isValid()) {
        $file = $request->file('avatar');

        // Store file with a secure random hash name on the public disk
        // Stored under storage/app/public/avatars/
        $path = $file->store('avatars', 'public');

        // Update the user record with the storage path
        auth()->user()->update(['avatar_url' => $path]);

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

    return back()->with('error', 'Upload failed. Please try again.');
}

Exposing Public Uploads: The Storage Symlink

Files saved to storage/app/public are not accessible via HTTP directly. You must create a symbolic link from your public directory by running: php artisan storage:link. This maps public/storage to storage/app/public, allowing you to display uploaded images with <img src="{{ asset('storage/' . $user->avatar_url) }}">.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between $request->input() and $request->query()?

$request->input() retrieves values from the entire request payload (including POST body and JSON). $request->query() specifically inspects only URL query string parameters (?page=2).

Q2. How does Laravel handle JSON payloads from mobile apps and React frontends?

If the request has an Content-Type: application/json header, Laravel parses the JSON payload automatically so you can access properties using $request->input('user.name') with dot-notation.

Q3. Where are files uploaded with $file->store('folder') saved by default?

By default, files are saved to storage/app/private/ (or the default disk configured in config/filesystems.php). Specifying the 'public' disk stores them in storage/app/public/.

Explore Related Laravel Tutorials & Next Steps

Broaden your backend architecture, REST API design, and enterprise production engineering expertise:

Form Request Validation & Custom Rules

Extract complex validation logic into dedicated FormRequest classes.

HTTP Responses, Redirects & Downloads

Respond to requests with flash messages, redirects, and JSON data.

Security Hardening: XSS & Sanitization

Sanitize file uploads, validate MIME types, and prevent malicious uploads.

HTML Form Handling & CSRF Protection

Verify @csrf tokens and submit multipart/form-data safely.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!