Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

Working with HTTP Requests in Laravel 12

When a browser or API client sends a request to a Laravel 12 route, Laravel creates an Illuminate\Http\Request object and passes it to your route closure or controller method. That object holds the request's URL, HTTP method, headers, input values, and uploaded files.

You use the request object to read incoming data, then validate that data before your application acts on it. Helpers like input() and integer() read or convert values for you, but they do not check whether those values meet your rules.

Receive and inspect the request

To access the current request, type-hint Request in your route closure or controller method. Laravel's service container, which builds the objects your methods ask for, automatically passes in the current request.

use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;

public function store(Request $request): RedirectResponse
{
    $name = $request->input('name');

    // Use the name after validating the submitted data.

    return redirect('/users');
}

The Illuminate\Http\Request documentation lists methods for inspecting the request path, URL, HTTP method, and headers. For example, path() returns the path without the host, fullUrl() includes the query string, and routeIs('admin.*') checks whether the current route name matches a pattern. If you only want values from the query string, call query().

Treat any header or token from the request as user-supplied data. Calling bearerToken() reads a token from the Authorization header, for instance, but you still have to verify who sent it. Laravel also warns that you should treat IP addresses as untrusted input and use them only for informational purposes.

Read input and check whether it was submitted

For ordinary request values, call input(). It reads from both the request body and the query string, while query() reads only from the query string. If a client sends a JSON body, it must set the Content-Type header to application/json so Laravel can parse the JSON and expose it through input().

$name = $request->input('name', 'Guest');
$filters = $request->query();

$archived = $request->boolean('archived');
$perPage = $request->integer('per_page', 15);
$versions = $request->array('versions');
$nameText = $request->string('name')->trim();

Laravel's typed helpers convert incoming values into the types your code expects. The boolean() helper returns true for 1, "1", true, "true", "on", and "yes", and false for everything else. The integer() helper converts a value to an integer and takes an optional default. If a value has to stay within certain limits or match a format, validate it separately. The Laravel 12 request methods also include date(), which you should only call after validating the input because an invalid date can throw an InvalidArgumentException.

You can also tell whether a user left a field out or submitted it empty. Calling has('name') checks whether the key is in the input, while filled('name') checks that the key is present and not an empty string. On the flip side, missing() checks whether the key was omitted, and isNotFilled() checks whether it is missing or empty. That distinction matters in cases like partial updates, where clearing a field means something different from leaving it untouched.

Validate before using submitted values

When a route only needs a few rules, validate the request directly in the controller and pass only the accepted values to the rest of your code:

$validated = $request->validate([
    'title' => ['required', 'string', 'max:255'],
    'body' => ['required', 'string'],
    'published' => ['sometimes', 'boolean'],
]);

// Use $validated rather than persisting all request input.

If the submitted data fails a rule, Laravel throws a validation exception. For a standard form submission, Laravel redirects the user back to the previous page. For an XHR (XMLHttpRequest) request, it returns JSON validation errors with HTTP status 422. You can find the full list of rules and response details in the Laravel validation documentation.

When you have a larger set of rules or want to tie authorization checks to a request, create a form request. A form request is a dedicated class that holds your validation rules and permission logic. Generate one with php artisan make:request StorePostRequest, add your rules to its rules() method, and type-hint the class in your controller. Laravel then runs validation before it calls your controller method.

public function store(StorePostRequest $request)
{
    $data = $request->validated();

    // Create the post from accepted fields.
}

Validate inline in the controller when the rules are short and only apply to one endpoint. Move them into a form request when you want a separate, reusable place for validation or authorization. Either way, read the accepted values with validated() or safe() instead of passing raw request input straight to your database.

Handle files and browser forms deliberately

You can access uploaded files through methods like file(). After you validate the upload, call store() to save it to a configured storage location, known as a filesystem disk:

$validated = $request->validate([
    'avatar' => ['required', 'file'],
]);

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

Pick the right storage disk and add validation rules that match what your endpoint allows. Laravel does not check a file's type or contents when you call store().

HTML forms only send GET and POST requests on their own. To send PUT, PATCH, or DELETE, use Laravel's method spoofing: submit a POST form with a hidden _method field, or add Blade's @method directive. For forms that hit Laravel's web routes, include @csrf as well. It adds a token that helps protect against cross-site request forgery, an attack that tricks a user's browser into sending an unwanted request. Laravel's routing documentation covers method spoofing and form routing in detail.

When Laravel redirects back to a form after an error, it can temporarily store the submitted values in the session so you can repopulate the fields with old(). Use flashOnly() or flashExcept() to control which fields Laravel stores, and leave out sensitive inputs like passwords.

Check proxy and host trust in deployment

If a reverse proxy or load balancer sits in front of your Laravel server, it changes how Laravel sees client IP addresses and HTTPS status. Configure trusted proxies in bootstrap/app.php so they match your actual infrastructure. Laravel also reads the incoming Host header when it builds absolute URLs, so configure trusted hosts for the hostnames your deployment should accept. The Laravel request documentation explains how to set up both options.

Do not rely on a request's IP address to prove who someone is. What Laravel sees as the client IP depends on your network path and proxy setup, and Laravel treats IP values as untrusted input. Verify your proxy and host settings against your live deployment, since forwarded headers and host values are not safe by default.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *