Skip to content

Instantly share code, notes, and snippets.

@stevebauman
Created October 31, 2019 14:39
Show Gist options
  • Save stevebauman/b55b165ee5cd3ee84c9abdddbf044882 to your computer and use it in GitHub Desktop.
Save stevebauman/b55b165ee5cd3ee84c9abdddbf044882 to your computer and use it in GitHub Desktop.
Google ReCAPTCHA Laravel Rule
<?php
namespace App\Rules;
use GuzzleHttp\Client;
use Illuminate\Contracts\Validation\Rule;
class ReCaptcha implements Rule
{
/**
* The recaptcha validation URL.
*
* @var string
*/
protected $url = 'https://www.google.com/recaptcha/api/siteverify';
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$client = new Client();
$response = $client->post($this->url,
['form_params'=>
[
'secret' => env('GOOGLE_RECAPTCHA_SECRET_KEY'),
'response' => $value
]
]
);
$body = json_decode((string) $response->getBody());
return $body->success;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return __('You must validate that you are human.');
}
}
<script src='https://www.google.com/recaptcha/api.js?hl={{ app()->getLocale() }}'></script>
<div class="g-recaptcha d-inline-block" data-sitekey="{{ config('google.recpatcha_site_key') }}"></div>
@if($errors->has('g-recaptcha-response'))
<div class="invalid-feedback">
{{ $errors->first('g-recaptcha-response') }}
</div>
@endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment