How to Use Validate Method in Laravel for Input Validation
In Laravel, you use the
validate method inside a controller to check incoming request data against validation rules. It automatically redirects back with errors if validation fails, or continues if data is valid.Syntax
The validate method is called on the $request object inside a controller method. It takes an array of rules where keys are input field names and values are validation rules.
Example parts:
$request->validate([...]): Runs validation on request data.- Array keys: input field names like
'email','password'. - Array values: rules like
'required','email','min:8'.
php
public function store(Request $request) { $validatedData = $request->validate([ 'email' => 'required|email', 'password' => 'required|min:8' ]); // Use $validatedData safely here }
Example
This example shows a controller method that validates user input for an email and password. If validation passes, it returns a success message. If it fails, Laravel automatically redirects back with error messages.
php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller { public function register(Request $request) { $validated = $request->validate([ 'email' => 'required|email', 'password' => 'required|min:8' ]); return response()->json([ 'message' => 'Validation passed!', 'data' => $validated ]); } }
Output
{"message":"Validation passed!","data":{"email":"user@example.com","password":"secret123"}}
Common Pitfalls
Common mistakes when using validate include:
- Not using the correct rule syntax (e.g., forgetting to separate rules with
|). - Trying to validate fields not present in the request.
- Not handling validation exceptions if you customize error handling.
- Using
validateoutside of a request context.
Always ensure your rules match the input names and use Laravel's built-in rules for best results.
php
<?php // Wrong: missing pipe separator between rules $request->validate([ 'email' => 'requiredemail' ]); // Right: $request->validate([ 'email' => 'required|email' ]);
Quick Reference
| Rule | Description |
|---|---|
| required | Field must be present and not empty |
| Field must be a valid email address | |
| min:value | Field must have minimum length or value |
| max:value | Field must have maximum length or value |
| confirmed | Field must match a confirmation field (e.g., password_confirmation) |
Key Takeaways
Use $request->validate() inside controller methods to check input data easily.
Pass an array of field names and validation rules separated by pipes.
Laravel auto-redirects back with errors if validation fails.
Always match validation rules to your form input names.
Common rules include required, email, min, max, and confirmed.