You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel验证失败/通过时设置回调并操作Session

Solution for Handling Attempt Session on Validation in Laravel Form Request

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 failedValidation method runs first, where we increment the attempt session 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 passedValidation method triggers right after validation passes, so we immediately clear the attempt session 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:32:37