The validate method on a request helps check if the data sent by a user is correct and safe before using it.
Validate method on request in Laravel
$request->validate([
'field_name' => 'rule1|rule2|rule3',
'another_field' => 'rule',
]);The validate method takes an array where keys are field names and values are rules as strings separated by |.
If validation fails, Laravel automatically redirects back with error messages.
$request->validate([
'email' => 'required|email',
'password' => 'required|min:8'
]);$request->validate([
'name' => 'required|string|max:255',
'age' => 'nullable|integer|min:18'
]);This controller method uses validate to check user input. If the data is good, it returns a JSON message with the valid data.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class UserController extends Controller { public function store(Request $request) { $validated = $request->validate([ 'username' => 'required|string|max:20', 'email' => 'required|email', 'password' => 'required|min:6' ]); // If validation passes, $validated contains only valid data return response()->json(['message' => 'User data is valid', 'data' => $validated]); } }
Validation rules are very flexible and can be combined to fit many needs.
Laravel automatically sends back errors and old input if validation fails, making it easy to show messages in forms.
You can customize error messages by passing a second argument to validate.
The validate method checks user input quickly and safely.
It uses simple rules written as strings to describe what is allowed.
If data is wrong, Laravel handles sending errors back automatically.