patternphplaravelTip
Form Request Validation: Authorization and Custom Rules
Viewed 0 times
form requestvalidationauthorizerulesvalidatedprepareForValidation403
Error Messages
Problem
Controllers become cluttered with validation logic. The authorize() method in Form Requests is misunderstood: returning false throws a 403 by default, but developers often return true without implementing real authorization.
Solution
Generate form requests with php artisan make:request. Put all validation rules in rules(). Use authorize() for policy checks or return true only for authenticated routes that rely on separate middleware. Use prepareForValidation() to transform input before validation runs. Access validated data with $request->validated().
Why
Form Requests move validation out of controllers, making controllers thin. They are auto-resolved by the service container and validation runs before the controller method is called, so you never receive invalid data.
Gotchas
- authorize() returning false sends a 403—don't return false just to skip authorization
- Use $request->safe()->only([...]) or $request->safe()->except([...]) for partial access to validated data
- Custom error messages are defined in the messages() method
- Validation rules for nested arrays use dot notation: 'items.*.price' => 'required|numeric'
Code Snippets
Form request with authorization
class UpdatePostRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()->can('update', $this->route('post'));
}
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'body' => ['required', 'string'],
];
}
}Revisions (0)
No revisions yet.