phpvalidationlaravel-5recaptcha

Google reCaptcha always resetting with laravel 5.1


I've searched about it on internet but it seems to be different. I'm using laravel5.1 and implemented google recaptcha. The scenario is, if the form was submitted and returns the validation with error, the recaptcha is resetting again and again, what I want is to not to reset it again, just staying as validated, because it annoys users to validate again and again. Do you have any idea about this?

Update: for code

public function postRegister(Request $request){
    // Validation
    $this->validate($request, [
        'username' => 'required|unique:users|max:20|min:3',
        'password' => 'required|min:6',
        'retype_password' => 'required|same:password',
        'email' => 'required|unique:users|email|max:255',
        'g-recaptcha-response' => 'required|recaptcha'
    ]);

    // Database save part here...

    return redirect()->route('register')->with('info', 'Success!');
}

Solution

  • This is a little more verbose now that I am trying to write the code, but you get the gist.

    Validate your Recaptcha field first. If it is valid, set a session variable to prevent it being rendered in your form again.

    public function postRegister(Request $request)
    {
        // Prepare validation rules
        $defaultRules = [
            'username' => 'required|unique:users|max:20|min:3',
            'password' => 'required|min:6',
            'retype_password' => 'required|same:password',
            'email' => 'required|unique:users|email|max:255',
        ];
        $recaptchaRules = [
            'g-recaptcha-response' => 'required|recaptcha',
        ];
    
        // Set session if recaptcha is valid
        if (Validator::make($request->all(), $recaptchaRules)->passes()) {
            session(['recaptcha' => true]);
        } 
        // Add recaptcha rules to default rules if failed to get single message bag with all errors
        else {
            $defaultRules = array_merge($defaultRules, $recaptchaRules);
        }
    
        // Validation
        $this->validate($request, $defaultRules);
    
        // Database save part here...        
    
        // Reset recaptcha validity so that the recaptcha is displayed on the next submission
        session(['recaptcha' => false]);
    
        return redirect()->route('register')->with('info', 'Success!');
    }
    

    Only output the Recaptcha field it if hasn't already been validated.

    @unless (session('recaptcha'))
        {{ Recaptcha::render() }}
    @endunless