How to Access HTTP Request Data in Laravel Controllers
This article explains multiple ways to obtain and work with the current HTTP request in Laravel, covering dependency injection in controllers, route parameters, route closures, URL and method retrieval, input handling (including defaults, arrays, and old data), existence checks, and file uploads, with practical code examples.
Laravel makes the current Illuminate\Http\Request instance available through dependency injection; you can type‑hint Request $request in a controller constructor or method and the service container will provide the request object.
When you also need route parameters, place them after the Request argument, e.g. public function update(Request $request, $id) , and Laravel will inject both the request and the route variable.
A route closure can receive the request directly: Route::get('/', function (Request $request) { ... }); , allowing you to access the request without a controller class.
To obtain the full URL or just the path, use $request->url() (no query string) or $request->fullUrl() (includes query string). The HTTP method is available via $request->method() .
Input data can be retrieved in several ways:
All input as an array: $input = $request->all();
Single value (with optional default): $name = $request->input('name', 'default');
Array notation for nested fields: $value = $request->input('products.0.name');
Query‑string only: $name = $request->query('name');
Only a subset: $data = $request->only(['username', 'password']);
All except some keys: $data = $request->except(['credit_card']);
Laravel also supports dynamic properties, so $request->name will first look for an input value and then a route parameter.
To check if a parameter exists, use $request->has('name') (or pass an array for multiple keys). To ensure the value is present and non‑empty, use $request->filled('name') .
Previous input values stored in the session can be accessed with $request->old('username') , which is useful for repopulating forms after validation failures.
File uploads are handled via the request as well: retrieve a file with $file = $request->file('photo'); , check its presence with $request->hasFile('photo') , validate it with $request->file('photo')->isValid() , and obtain its path or extension using $request->photo->path() and $request->photo->extension() .
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.