Master Laravel Request Handling: DI, Input Retrieval, Cookies & File Uploads

This guide explains how to inject the Illuminate\Http\Request into Laravel controllers, retrieve route parameters, access request paths, methods, query strings, filter input, work with old input, manage cookies, handle uploaded files, and configure trusted proxies for accurate HTTPS detection.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Master Laravel Request Handling: DI, Input Retrieval, Cookies & File Uploads

Injecting the Request Instance

Type‑hint Illuminate\Http\Request in a controller method or route closure to have Laravel automatically inject the current HTTP request.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller {
    public function store(Request $request) {
        $name = $request->input('name');
        // ...
    }
}

If a route also provides parameters, list them after the request dependency:

Route::put('user/{id}', 'UserController@update');
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller {
    public function update(Request $request, $id) {
        // ...
    }
}

In a route closure you can inject the request directly:

use Illuminate\Http\Request;

Route::get('/', function (Request $request) {
    // ...
});

Request Path & Method Helpers

path()

– returns the request path (e.g. foo/bar for http://example.com/foo/bar). is($pattern) – checks the path against a pattern; * works as a wildcard. url() – URL without query string. fullUrl() – URL including query string. method() – HTTP verb. isMethod($verb) – verifies the verb.

$uri = $request->path();
if ($request->is('admin/*')) { /* ... */ }

$url  = $request->url();
$full = $request->fullUrl();

$method = $request->method();
if ($request->isMethod('post')) { /* ... */ }

PSR‑7 Request Support

To work with a PSR‑7 request, install the Symfony bridge and Diactoros packages:

composer require symfony/psr-http-message-bridge
composer require zendframework/zend-diactoros

Then type‑hint Psr\Http\Message\ServerRequestInterface in a controller or route closure:

use Psr\Http\Message\ServerRequestInterface;

Route::get('/', function (ServerRequestInterface $request) {
    // ...
});
Returning a PSR‑7 response from a route or controller will be automatically converted to a Laravel response.

Input Filtering & Normalization

Laravel’s global middleware stack includes TrimStrings and ConvertEmptyStringsToNull. They trim string inputs and convert empty strings to null. To disable them, remove the middleware from the $middleware array in App\Http\Kernel.

Retrieving Input

All input data : $input = $request->all(); Single value : $name = $request->input('name'); – optional default: $request->input('name', 'Sally'); Nested data (dot notation) : $product = $request->input('products.0.name'); or $names = $request->input('products.*.name'); Query string only : $name = $request->query('name'); – default: $request->query('name', 'Helen'); – all query data: $all = $request->query(); Dynamic property access : $name = $request->name; (falls back to route parameters if not present in the payload).

JSON payload : When Content-Type: application/json, input() works with JSON keys using dot notation, e.g. $request->input('user.name'); Partial input : $subset = $request->only(['username', 'password']); or $except = $request->except(['credit_card']); Existence checks : $request->has('name');, $request->has(['name', 'email']);,

$request->filled('name');

Old Input (Flashing)

Flash the current request data to the session:

$request->flash();
$request->flashOnly(['username', 'email']);
$request->flashExcept('password');

When redirecting, withInput() automatically flashes the input:

return redirect('form')->withInput();
return redirect('form')->withInput($request->except('password'));

Retrieve old data via the request object or the global old() helper in Blade:

$username = $request->old('username');
// Blade example (escaped for safety)
<?php echo '<input type="text" name="username" value="{{ old('username') }}">'; ?>

Cookies

Reading cookies :

$value = $request->cookie('name');
// or using the facade
use Illuminate\Support\Facades\Cookie;
$value = Cookie::get('name');

Attaching cookies to a response :

return response('Hello World')
    ->cookie('name', 'value', $minutes);

// Full signature
return response('Hello World')
    ->cookie('name', 'value', $minutes, $path, $domain, $secure, $httpOnly);

Queueing cookies :

Cookie::queue(Cookie::make('name', 'value', $minutes));
Cookie::queue('name', 'value', $minutes);

Generating a Cookie instance :

$cookie = cookie('name', 'value', $minutes);
return response('Hello World')->cookie($cookie);

File Uploads

Retrieving uploaded files :

$file = $request->file('photo');
// or dynamic property
$file = $request->photo;

Checking existence & validity :

if ($request->hasFile('photo')) { /* ... */ }
if ($request->file('photo')->isValid()) { /* ... */ }

File path & extension :

$path      = $request->photo->path();
$extension = $request->photo->extension();

Storing files (unique name):

$path = $request->photo->store('images');
$path = $request->photo->store('images', 's3');

Storing with a custom name :

$path = $request->photo->storeAs('images', 'filename.jpg');
$path = $request->photo->storeAs('images', 'filename.jpg', 's3');

Configuring Trusted Proxies

When behind a load balancer that terminates TLS, Laravel may generate HTTP links instead of HTTPS. Add the App\Http\Middleware\TrustProxies middleware and list trusted proxy IPs in the $proxies property. Choose the appropriate header constant for your environment.

<?php
namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware {
    /**
     * Trusted proxy IP addresses.
     * @var array|string
     */
    protected $proxies = ['192.168.1.1', '192.168.1.2'];

    /**
     * Header used to detect the proxy.
     * @var int
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
To trust all proxies (e.g., on AWS ELB), set $proxies = '*'; and use Request::HEADER_X_FORWARDED_AWS_ELB as the header constant.
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

file uploaddependency-injectioncookiesLaravelInput HandlingHTTP requestTrusted Proxies
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.