How to Validate Request in Laravel: Simple Guide
In Laravel, you validate a request by calling the
validate() method on the request object inside a controller. You pass an array of rules to validate() that define what input is required and how it should be checked.Syntax
Use the validate() method on the request object. Pass an array where keys are input field names and values are validation rules.
- request()->validate([...]): Validates the incoming request.
- rules: Define required fields, types, formats, etc.
- If validation fails, Laravel automatically redirects back with errors.
php
public function store(Request $request) { $validatedData = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users,email', 'age' => 'nullable|integer|min:18' ]); // Use $validatedData safely here }
Example
This example shows a controller method validating a user registration form. It requires a name, a unique email, and optionally an age that must be at least 18 if provided.
php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller { public function register(Request $request) { $validated = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users,email', 'age' => 'nullable|integer|min:18' ]); return response()->json(['message' => 'Validation passed', 'data' => $validated]); } }
Output
{"message":"Validation passed","data":{"name":"John Doe","email":"john@example.com","age":25}}
Common Pitfalls
- Not returning or handling validation errors causes confusing behavior.
- Using incorrect rule syntax like
'required:email'instead of'required|email'. - Forgetting to import
Illuminate\Http\Requestin the controller. - Not validating all user inputs, which can cause security issues.
php
public function store(Request $request) { // Wrong: using colon instead of pipe $request->validate([ 'email' => 'required:email' ]); // Right: $request->validate([ 'email' => 'required|email' ]); }
Quick Reference
Here are some common validation rules you can use in Laravel:
| Rule | Description |
|---|---|
| required | Field must be present and not empty |
| string | Field must be a string |
| Field must be a valid email address | |
| unique:table,column | Field must be unique in the database table column |
| nullable | Field can be null or empty |
| integer | Field must be an integer |
| min:value | Minimum value or length |
| max:value | Maximum value or length |
Key Takeaways
Use
request()->validate() with an array of rules to validate input easily.Validation automatically redirects back with errors if input is invalid.
Always validate all user inputs to keep your app secure.
Use pipe
| to separate multiple validation rules for a field.Check Laravel docs for many built-in validation rules to fit your needs.