Q36. What is Form Request validation?
Solution and explanation
A Form Request is a dedicated class that holds the authorization check and validation rules for one request. Laravel runs it before the controller method; if validation fails the controller never executes.
php artisan make:request StoreOrderRequest
class StoreOrderRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()->can('create', Order::class);
}
public function rules(): array
{
return [
'shipping_address_id' => ['required', Rule::exists('addresses', 'id')->where('user_id', $this->user()->id)],
'items' => ['required', 'array', 'min:1', 'max:50'],
'items.*.product_id' => ['required', 'integer', 'exists:products,id'],
'items.*.quantity' => ['required', 'integer', 'min:1', 'max:10'],
'coupon' => ['nullable', 'string', 'max:30'],
];
}
public function messages(): array
{
return ['items.min' => 'Your cart is empty.'];
}
protected function prepareForValidation(): void
{
$this->merge(['coupon' => $this->coupon ? strtoupper(trim($this->coupon)) : null]);
}
}
Controller:
public function store(StoreOrderRequest $request, OrderService $orders)
{
$order = $orders->place($request->user(), $request->validated());
return (new OrderResource($order))->response()->setStatusCode(201);
}
What happens on failure: for browser requests Laravel redirects back with errors and old input; for JSON requests it returns 422 with an errors object.
Why it is better than validating in the controller:
- The controller shows business flow only.
- Rules are reusable and unit-testable.
- authorize() keeps permission checks next to the input they protect.
- Notice the address rule: it validates that the address belongs to this user, a security check, not just a format check.
Advanced hooks: withValidator() for cross-field rules, after() (Laravel 10+), and passedValidation() to normalise data.
Interview answer: "Form Requests hold authorization and validation, run before the controller, return 422 or redirect automatically, and keep controllers clean. I also use them to validate ownership, not just format."
