以下是如何通过扩展来正确执行此操作Validator
,但是此解决方案使用 google/recaptcha 包(这比使用 CURL 优雅得多)。
composer require google/recaptcha "~1.1"
创建一个新的配置值recaptcha_secret_key
and recaptcha_site_key
in config/app.php
或另一个自定义配置文件。
In AppServiceProvider
boot()
method:
Validator::extend('recaptcha', function ($attribute, $value, $parameters, $validator) {
$recaptcha = new ReCaptcha(config('app.recaptcha_secret_key'));
$resp = $recaptcha->verify($value, request()->ip());
return $resp->isSuccess();
});
In resources/lang/validation.php
add:
'recaptcha' => 'The :attribute answer is invalid.',
另外,将此添加到attributes
数组位于同一文件中,以使错误消息更好:
'g-recaptcha-response' => 'reCAPTCHA',
在视图文件中,您要显示 reCAPTCHA,例如contact.blade.php
:
<div class="g-recaptcha" data-sitekey="{{ config('app.recaptcha_site_key') }}"></div>
<script src="https://www.google.com/recaptcha/api.js"></script>
Add data-size="invisible"
如果你想让它不可见的话,等等。
最后,将新的验证规则添加到您的控制器中:
'g-recaptcha-response' => 'recaptcha'