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

Validation vs. Sanitization in Laravel Requests

When a Laravel endpoint receives form or API data, validation checks whether the data meets rules set in the code. Sanitization changes data by removing or modifying content according to a policy. Passing validation does not change a value or make it safe for every later use.

Laravel middleware, code that runs before the request reaches application code, cleans up some input. A Form Request can also change data before or after validation. Use validation to enforce requirements. Change a field’s data when its rules call for it. Protect data where the code uses or displays it.

Validation checks; it does not rewrite

A validation rule checks whether a value meets a requirement. An email rule checks whether a value has an accepted email format. Laravel’s validate() method and Form Request rules let code define these checks.

When the rules pass, Laravel continues handling the request. When they fail, Laravel raises a validation exception and returns a response for that request, such as a redirect or a JSON response with errors. Passing the rules means only that the input met the checks the code specified. For example, a valid date is not necessarily suitable for a business operation unless the rules check that too.

Use validated() or safe() to pass only fields that passed validation to later code. They return validated data without cleaning or changing its values. If a rule accepts a string, the string’s content stays the same.

Validation also does not show that the requester has permission to access a database record. Check authorization separately. Use parameterized queries for database queries instead of relying on input filtering. The OWASP input validation guidance treats validation, authorization, and other security controls as separate responsibilities.

Laravel cleanup happens outside the validation rules

Laravel 13.x includes TrimStrings and ConvertEmptyStringsToNull in the default global middleware stack. Middleware is code that runs before application code handles a request. These two middleware trim incoming strings and turn empty strings into null. The HTTP request documentation explains these defaults and how to change or skip them. Applications can configure the middleware stack, so check the configuration for the Laravel version in use.

This cleanup affects validation. If an optional form field arrives as an empty string, Laravel passes null to the validator instead. Add the nullable rule to accept null; otherwise, validation can reject a field that appeared empty in the form.

A Form Request provides prepareForValidation() to change data before the rules run. For example, code can put a submitted slug, a short text value used in a URL, into a consistent format before validation:

protected function prepareForValidation(): void
{
    $this->merge([
        'slug' => Str::slug($this->input('slug')),
    ]);
}

Here, Str::slug() changes the value, and the validation rules check the changed value. Use this approach when the field has a clear rule for putting values into a consistent format. Do not remove characters from arbitrary text just because they look unusual. Doing so can discard legitimate user input.

Laravel also provides passedValidation() to change data after validation succeeds. Choose the hook based on which version of the value the rules should check. Make a change before validation if it affects whether the value is acceptable. If code changes the value afterward, make sure later code uses the intended version.

Protect data where the code uses it

A value that passes input rules still needs protection suited to where the code uses it. When code displays ordinary text in HTML, it should encode the output for that context so the browser treats the text as text. If users are allowed to submit HTML, use a maintained HTML sanitizer that permits the intended markup. Removing a <script> tag alone does not reliably make arbitrary HTML safe, as the OWASP XSS prevention guidance explains.

The term “sanitization” has different meanings in different contexts. Laravel’s Form Request documentation uses it broadly for changes made in preparation hooks, such as generating a slug. OWASP uses it for changing potentially dangerous content according to a security policy. Its security terminology guidance distinguishes sanitization from normalization, which puts data into a consistent format, and output encoding, which prepares data for display. Describe the actual change. Examples include trimming whitespace and changing an empty string to null. Other examples are normalizing a slug and sanitizing permitted HTML.

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 *