Naar de inhoud
Recognized by Laravel Match je project Contact

Gebruik Form Request-classes

Voor het laatst bijgewerkt op:

Beschrijving

Verplaats de validatie en autorisatie van requests naar toegewijde Form Request-classes in plaats van naar controllers.

Aanbevolen situatie

Gebruik dit voor controller-acties en endpoints die niet-triviale gebruikersinvoer accepteren.

Menselijke begeleiding

Laravel Form Request-classes halen validatie- en autorisatielogica uit controllers en plaatsen deze in toegewijde classes. Door een Form Request te type-hinten in een controllermethode wordt automatisch de validatie en autorisatie uitgevoerd voordat de methode draait. Zo blijven controllers dun en is de validatielogica herbruikbaar.

Waarom

  • Scheiding van verantwoordelijkheden: Validatielogica leeft in een eigen class en vervuilt de controllermethoden niet
  • Herbruikbaarheid: Dezelfde Form Request kan in meerdere controllers of acties worden gebruikt
  • Automatische uitvoering: Het type-hinten van de Form Request voert validatie en autorisatie automatisch uit, geen handmatige validate()-aanroep nodig
  • Veiligheid: Het gebruik van $request->validated() zorgt ervoor dat alleen gevalideerde data aan mass operations wordt doorgegeven, waardoor niet-gevalideerde velden niet kunnen doorlekken

Geschikt voor

  • Elke controllermethode die gebruikersinvoer accepteert
  • Formulieren met meerdere validatieregels
  • Endpoints waar autorisatie en validatie nauw met elkaar samenhangen
  • API's waar consistente validatie-foutmeldingen belangrijk zijn

Minder geschikt voor

  • Extreem eenvoudige endpoints met één of twee triviale validatieregels
  • Closure-gebaseerde routes in prototyping- of testscenario's

Voorbeelden

Haal validatie naar Form Requests

// Bad: inline validation in controllers
public function store(Request $request)
{
    $request->validate([
        'title' => 'required|max:255',
        'body' => 'required',
    ]);
}

// Good: dedicated Form Request class
public function store(StorePostRequest $request)
{
    Post::create($request->validated());
}

Gebruik altijd validated()

Gebruik nooit $request->all() voor mass operations:

// Bad: includes unvalidated fields
Post::create($request->all());

// Good: only validated data
Post::create($request->validated());

Geef de voorkeur aan array-notatie voor regels

Array-syntax is beter leesbaar en combineert netjes met Rule::-objecten. Geef er de voorkeur aan in nieuwe code, maar sluit aan bij de bestaande conventie:

// Preferred for new code
'email' => ['required', 'email', Rule::unique('users')],

// Follow existing convention if the project uses string notation
'email' => 'required|email|unique:users',

Gebruik Rule::when() voor voorwaardelijke validatie

'company_name' => [
    Rule::when($this->account_type === 'business', ['required', 'string', 'max:255']),
],

Gebruik de after()-methode voor custom validatie

Gebruik after() in plaats van withValidator() voor custom validatielogica die van meerdere velden afhangt:

public function after(): array
{
    return [
        function (Validator $validator) {
            if ($this->quantity > Product::find($this->product_id)?->stock) {
                $validator->errors()->add('quantity', 'Not enough stock.');
            }
        },
    ];
}

Meer info

Boost-richtlijn

---
title: Use Form Request Classes
description: Move request validation and authorization into dedicated Form Request classes instead of controllers.
recommended_situation: Use for controller actions and endpoints that accept non-trivial user input.
---

- Create Form Request classes for request validation and authorization instead of validating inline in controllers.
- Type-hint the Form Request on controller actions so Laravel runs authorization and validation automatically.
- Pass `$request->validated()` downstream for mass assignment, actions, or services; do not use `$request->all()`.
- Prefer readable rule definitions and keep conditional or cross-field validation inside the Form Request.
Skill

Laravel Boost Skill

Gebruik deze skill om de richtlijn rechtstreeks toe te passen met een AI-assistent.

Use this skill when a Laravel task touches this best practice. It is self-contained so it can be installed independently by Laravel Boost or another agent-skill system.

## Core Guidance



## Why It Matters

- Apply the best practice consistently and keep the implementation focused.

## Apply When

- Laravel work that directly overlaps with this practice.

## Be Careful When

- Tasks outside this practice; use a more specific skill instead.

## Canonical Source

- Full best practice: https://github.com/Dutch-Laravel-Foundation/best-practices/blob/main/routing/use-form-request-classes/BEST_PRACTICE.md
- Dutch translation: https://github.com/Dutch-Laravel-Foundation/best-practices/blob/main/routing/use-form-request-classes/translations/nl.md

## Workflow

1. Inspect the user's Laravel code before recommending changes.
2. Identify the narrow rule from this best practice that applies to the task.
3. Prefer Laravel's built-in conventions and documented APIs over custom abstractions.
4. Keep examples focused on this practice; reference other skills or practices when the task crosses boundaries.
5. Verify code changes with the project's available tests, linters, static analysis, or framework checks.

## Review Checklist

- The recommendation is Laravel-specific and grounded in this practice.
- Code examples use realistic Laravel file names, class names, and method names.
- The advice avoids mixing unrelated architecture, deployment, security, or testing topics.
- Related practices are mentioned when useful, but not re-explained in full.
- Dutch output, when requested, keeps framework and API names intact.