Search code examples
laravelrecaptcharecaptcha-v3

In Laravel with ReCaptcha V3, how do I access the "score" returned from a rule?


In Laravel, I am setting up Google ReCaptcha V3 which now returns a "score". I've managed to setup a validation rule to allow my form to submit (all working), but this is only returning true or false to pass the validation.

How do I base this on the score instead?

I'm using this composer package to help me out - https://github.com/google/recaptcha

This is in my controller (where I am sending the token to validate with the server):

// validation
$this->validate( $request, array(
    'g_recaptcha_response' => ['required', 'string', new Captcha()]
));

This is the rule:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use ReCaptcha\ReCaptcha;

class Captcha implements Rule
{

    public function __construct()
    {
        //
    }

    public function passes($attribute, $value)
    {
        $recaptcha = new ReCaptcha('SECRET');
        $response = $recaptcha->verify($value, $_SERVER['REMOTE_ADDR']);
        return $response->isSuccess();
    }

    public function message()
    {
        return 'Are you a robot?';
    }

}

Can I access the class somehow from the controller? I can see in the package that I need to use ->getScore() but I don't know how to access it?


Solution

  • As you are doing in the validation rule, you can also get the score in controller :

    public function something(YourRequest $request){
    
        $recaptcha = new ReCaptcha('SECRET');
        $response = $recaptcha->verify($request->g_recaptcha_response, $request->ip());
        $score =  $response->getScore();
    }
    

    More available methods of response can be found here