Validate a request at its boundary
Turn untrusted input into a small, reliable command.
Define the contract
Write down required fields, their accepted types, and cross-field rules before writing a controller. A missing `resource_id` is different from an invalid identifier, and an end time must be later than a start time. Collect field-specific errors so the caller can show the user what to correct.
Normalize only after checking
Do not trust a client-side form or a TypeScript interface to protect the server. Validate raw input at the HTTP boundary, then create a typed command or value object. Pass only allowed fields onward. This prevents extra keys from slipping into mass assignment and keeps business logic independent of the request object.
$data = $request->validate([
'resource_id' => ['required', 'integer', 'min:1'],
'start_minute' => ['required', 'integer', 'min:0'],
'end_minute' => ['required', 'integer', 'gt:start_minute'],
]);
Test the rejection path
Check a valid request, a missing field, a string where an integer is required, and equal start and end times. Assert that invalid requests create no booking. Keep authorization separate from validation: a correctly shaped request can still target a resource that the user may not access.
Check your understanding
Why should validated fields be passed onward instead of the entire request body?
Show explanation
The validated subset excludes unexpected keys and gives downstream code a known shape. Authorization must still be checked separately.
You can read for free. Create an account to save your progress.
← Previous lesson: Values, types and array keys Next lesson: Make related writes atomic →Put this lesson into practice
A practice activity at this level in the same module.
Try: Create a URL-safe slugFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.