如何在Laravel验证失败/通过时设置回调并操作Session
Hey there! Let's get your session-based attempt count working with your AuthRequest validation. Laravel's FormRequest has built-in hooks that let you run code right after validation passes or fails—perfect for your use case. Here's how to adjust your code:
Step 1: Fix Your AuthRequest Structure
First, let's move your validation rules into the standard rules() method and add the validation hook methods to handle session updates:
class AuthRequest extends FormRequest { // Adjust this based on your app's authorization requirements public function authorize() { return true; } // Define your validation rules here (the proper Laravel FormRequest way) public function rules(){ return [ 'first_name' => ['required','min:2','max:30',new PersonNameRule], 'last_name' => ['required','min:2','max:30',new PersonNameRule], 'username' => ['required','confirmed',new UsernameRule] ]; } // Triggered automatically when validation fails protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator) { // Update the attempt count: start at 0 if session doesn't exist, then increment $attemptCount = session('attempt', 0) + 1; session(['attempt' => $attemptCount]); // Call the parent method to keep Laravel's default validation failure behavior parent::failedValidation($validator); } // Triggered automatically when validation passes protected function passedValidation() { // Remove the attempt session key entirely session()->forget('attempt'); } }
Step 2: Simplify Your Controller Code
Since FormRequest automatically handles validation when you type-hint it in your controller method, you don't need the custom store() method anymore. You can access validated data directly:
public function store(AuthRequest $request) { // Validation is already complete here—attempt session is cleared if passed $validatedData = $request->validated(); // Get only the validated fields return $request->all(); // Or return $validatedData if you don't need unvalidated fields }
How This Works
- On validation failure: The
failedValidationmethod runs first, where we increment theattemptsession value (defaulting to 0 if the session key doesn't exist yet). We then call the parent method to let Laravel handle standard error responses. - On validation success: The
passedValidationmethod triggers right after validation passes, so we immediately clear theattemptsession to reset the count.
This approach follows Laravel's best practices, keeps your validation logic centralized, and ensures your session updates happen automatically without extra controller code.
内容的提问来源于stack exchange,提问作者schutte

