Skip to content

Instantly share code, notes, and snippets.

@pravnkay
Last active November 21, 2020 01:18
Show Gist options
  • Save pravnkay/7fa607f89b4e4999e180a3d2a5e5f9f3 to your computer and use it in GitHub Desktop.
Save pravnkay/7fa607f89b4e4999e180a3d2a5e5f9f3 to your computer and use it in GitHub Desktop.
Using Google Recaptcha v3 in Laravel

Using Google's Recaptcha in Laravel

Google’s recaptcha is an effective way to curb the spammers in your web forms. It helps differentiate the bots from humans using a scoring system. Let me explain how I use it in my Laravel apps on pages that has a public web form.

Support

You can read more on this in my Medium blog post here. Do let me know your thoughts through comments or through mail github@praveen.bulc.club

Have a good day !

'recaptcha_key' => env('GOOGLE_RECAPTCHA_KEY'),
'recaptcha_secret' => env('GOOGLE_RECAPTCHA_SECRET'),
use App\Http\Controllers\Controller;
use App\Rules\Recaptcha;
class FunctionController extends Controller
{
public function create(array $input)
{
Validator::make($input, [
'recaptcha_response' => [
'required',
new Recaptcha,
],
// ... further code ...
GOOGLE_RECAPTCHA_KEY="<your-site-key>"
GOOGLE_RECAPTCHA_SECRET="<your-site-secret>"
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Recaptcha implements Rule
{
public function passes($attribute, $value)
{
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = config('app.recaptcha_secret');
$recaptcha_response = $value;
$recaptcha_response = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha_response_decoded = json_decode($recaptcha_response);
if (!$recaptcha_response_decoded->success) {
return false;
}else if($recaptcha_response_decoded->score < 0.5){
return false;
} else {
return $recaptcha_response_decoded->success;
}
}
public function message()
{
return [
'recaptcha' => 'Human validation error. Please try again.'
];
}
}
// ... blade template code ...
<script src="https://www.google.com/recaptcha/api.js?render={{config('app.recaptcha_key')}}"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('{{config('app.recaptcha_key')}}', { action: 'register' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
});
});
</script>
<form>
@csrf
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
@error('recaptcha_response')
<span class="invalid-feedback d-block mb-5" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
// ... further code ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment