Validation
| Inline validate() | |
| Form requests | |
| Common rules | |
| Custom messages |
Inline validate()
The fastest way to guard input is the validate method on the request object. It checks the rules, and on failure it sends the visitor back with the errors and the old input.
On success it returns only the fields that passed, so the controller works with clean data from that point on.
$validated = $request->validate([ "name" => "required|string|max:255", "email" => "required|email", ]);
Form requests
When rules grow past a few lines, move them into a form request class built with make:request. The controller then type hints the request and stays short.
Authorization lives in the same class: the authorize method returns true when the current visitor may perform the action.
class StorePostRequest extends FormRequest { public function authorize(): bool { return true; } public function rules(): array { return [ "title" => "required|string|max:255", "body" => "required|string", ]; } }
Common rules
A small set of rules covers most forms: required marks a field as mandatory, string and integer check the type, and max and min limit the length or the value.
Specialized rules such as email, unique, and confirmed shape the rest of the form without extra code.
$validated = $request->validate([ "password" => "required|string|min:8|confirmed", "email" => "required|email|unique:users", "age" => "nullable|integer|min:0", ]);
Custom messages
Default messages are clear enough for most cases, but a form request can define its own words with a messages method. Match each rule with the field name, a dot, and the rule name.
Custom messages help visitors fix the exact field instead of guessing what went wrong.
public function messages(): array { return [ "title.required" => "A title is required.", "email.email" => "That address does not look like an email.", ]; }
Next: Auth intro
Article author: Arthur Isaev