Course outline

Laravel / Basic: request and data foundations / Lesson 5

Validation, middleware, and CSRF boundaries

Reject malformed input and cross-site request forgery without confusing either with authorization. Follow validated data, middleware context, and session token comparison in isolated component examples.

About 4 min readContent reviewed
On this page

Lesson goals

  • Define field shape and domain rules explicitly.
  • Explain middleware order and response differences.
  • Distinguish CSRF token checks from session and browser integration.

Validation establishes a bounded input contract

A validation rule set describes required fields, types, lengths, ranges, and relationships appropriate to the action. It does not establish ownership or permission, and a valid record can still be unsafe to mass assign wholesale. Use validated selected fields when invoking domain work and convert representations explicitly where required. Laravel validation rules such as integer can accept suitable numeric strings without turning the stored value into an integer automatically. Missing, nullable, and prohibited fields express different policies. Keep these choices deliberate rather than collecting rules until a form happens to pass. Test malformed arrays as well as ordinary text values.

Inspect rule outcomes without a web application

The local validator factory uses an owned array translation loader and literal data. It checks required title and minimum positive seats, then reports the error keys rather than depending on a fully configured language catalog. No Form Request, route, CSRF middleware, or browser redirect is run. This isolates rule behavior; the full application can normalize empty strings through middleware and choose redirect or JSON error responses based on request context. Test those behaviors separately. Do not infer that a passing rule factory means an action was authorized or that a failed form preserves old input and accessible errors correctly.

php Rule-level validation with owned dependencies
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
$translator = new Illuminate\Translation\Translator(new Illuminate\Translation\ArrayLoader(), 'en');
$factory = new Illuminate\Validation\Factory($translator);
$validator = $factory->make(['title' => '', 'seats' => 0], [
    'title' => ['required', 'string'], 'seats' => ['required', 'integer', 'min:1'],
]);
echo $validator->passes() ? "valid\n" : "invalid\n";
echo implode(',', $validator->errors()->keys()), PHP_EOL;
Expected output
invalid
title,seats

Both fields fail their intended rules. This does not test HTTP 422 rendering or redirect/session behavior.

Middleware composition changes the meaning of a request

Middleware can normalize input, start a session, establish authentication, verify request origin requirements, and bind route data. Order and group membership matter: an API route and a browser session route may intentionally have different stacks. In the Laravel 12 application skeleton, middleware customization belongs to the documented bootstrap configuration rather than assumptions copied from older skeletons. Avoid disabling a whole stack to fix a failing feature test; first identify which precondition is missing. A request expecting JSON can receive a different validation representation from a traditional browser form even when the same rules fail.

CSRF checks a session-linked request token

Browser session actions need a CSRF strategy because cookies may be attached automatically to requests. Laravel supports token mechanisms described by its web middleware and frontend integration contracts. A matching token is not authentication or object authorization. The isolated example exposes the framework comparison method with a synthetic session and encryption key; it does not dispatch a real request or test cookie scope. Full middleware may bypass checks under particular test conditions, so a feature test passing without a token is not proof that the deployed browser path accepts tokenless state changes. Verify the actual stack and testing assumptions.

php Synthetic token comparison, not browser CSRF integration
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
$app = new Illuminate\Foundation\Application(__DIR__);
$encrypter = new Illuminate\Encryption\Encrypter(str_repeat('d', 32), 'AES-256-CBC');
$middleware = new class($app, $encrypter) extends Illuminate\Foundation\Http\Middleware\VerifyCsrfToken {
    public function matches(Illuminate\Http\Request $request): bool { return $this->tokensMatch($request); }
};
$session = new Illuminate\Session\Store('synthetic', new Illuminate\Session\ArraySessionHandler(120));
$session->put('_token', 'synthetic-course-token');
$request = Illuminate\Http\Request::create('/enroll', 'POST', ['_token' => 'synthetic-course-token']);
$request->setLaravelSession($session);
echo $middleware->matches($request) ? "match\n" : "mismatch\n";
$request->request->set('_token', 'different');
echo $middleware->matches($request) ? "match\n" : "mismatch\n";
Expected output
match
mismatch

Only the protected comparison is exercised. No environment file, application bootstrap, real session storage, or browser cookie is loaded.

Diagnose rejection before weakening protection

For a 419-like token rejection, inspect the session lifecycle, cookie host/path/security policy, frontend token source, and the route middleware group. For validation errors, inspect the actual payload shape, normalization, and response negotiation. A malformed JSON body, missing session, and wrong field rule are different causes that need different repairs. Keep error details safe and preserve legitimate entered values for correction. Test allowed and rejected operations with synthetic accounts and no forbidden side effects. Removing CSRF middleware, trusting hidden prices, or broadly allowing fields can make a symptom disappear while creating a new vulnerability.

Common errors and fixes

Validated input is treated as permission

Why it happens
Field rules replace actor/object policy checks.
How to fix it
Authorize the actual operation independently.
Prevent it next time
Test another owner with otherwise valid data.

CSRF is disabled to remove a 419 response

Why it happens
The session/token precondition is not diagnosed.
How to fix it
Repair cookie, session, or token transport for the intended stack.
Prevent it next time
Verify both matching and rejected synthetic requests.

An integer rule is assumed to cast the field

Why it happens
Validation and representation conversion are conflated.
How to fix it
Convert validated values deliberately before strict domain calls.
Prevent it next time
Assert type as well as accepted range at the boundary.

Check your understanding

1. A validation factory passes title and seats. What remains unproven?

Show worked solution

The route stack, CSRF transport, actor permission, response representation, session old-input behavior, and durable write effects remain separate questions. Add targeted integration checks for the feature instead of calling rule acceptance a complete secure submission.

2. Why might a feature test accept a POST without proving deployed CSRF behavior?

Show worked solution

The test environment or middleware setup may intentionally bypass CSRF checks. Verify the test stack and add controlled evidence for the browser-session token contract. Do not weaken production protection merely to align it with an intentionally simplified test context.

Key takeaways

  • Validation, middleware context, CSRF, and authorization are separate contracts.
  • Diagnose the missing precondition before changing security policy.

Official references