Laravel Form Validation: Practical Tips and Examples
Clean, secure form validation in Laravel with Form Requests, custom messages, conditional rules and validated data.
Validation is your first line of defence against bad data. Laravel makes it easy, and a few habits keep it clean as your app grows.
Validate in the controller (small forms)
$data = $request->validate([
'name' => ['required', 'string', 'max:120'],
'email' => ['required', 'email', 'max:190'],
'message' => ['required', 'string', 'min:20', 'max:5000'],
]);
If validation fails, Laravel redirects back with the errors and old input automatically (or returns JSON with a 422 status for API requests).
Use Form Requests for bigger forms
php artisan make:request ContactRequest
public function rules(): array
{
return [
'email' => ['required', 'email'],
'phone' => ['nullable', 'regex:/^[0-9+\-\s()]{6,40}$/'],
];
}
public function messages(): array
{
return ['phone.regex' => 'Please enter a valid phone number.'];
}
Type-hint it in your controller method and validation runs before your code does.
Only use validated data
Save $request->validated() (or $request->safe()->only([...])) instead of $request->all(). Unexpected fields never reach your database.
Conditional rules
'company' => ['required_if:type,business', 'nullable', 'string'],
'discount_code' => ['sometimes', 'exists:discounts,code'],
Arrays and nested input
'items' => ['required', 'array', 'max:10'],
'items.*.name' => ['required', 'string', 'max:100'],
'items.*.qty' => ['required', 'integer', 'min:1'],
Unique rules when editing
use Illuminate\Validation\Rule;
'email' => ['required', 'email', Rule::unique('users')->ignore($user->id)],
Bonus: simple spam protection
Add a hidden "honeypot" field that must stay empty, and rate-limit the form route with the throttle middleware. Together they stop most automated spam without annoying real visitors.
Need help with your website?
I build fast, SEO-ready websites and web applications.