There are plenty of options to prevent spam, but captcha is one of the best to use. When talking about captcha, the first thing will be in mind is weird characters seen on the online forms. Here we talk about Google’s Recapthca integration to your Laravel application.
First thing is first, let’s go to https://www.google.com/recaptcha website and register our new site there. If you are redirecting to a intro page, just click on the my captcha’s link on the top. There you will see a form with title, Register a new site. Create your new site and generate secret keys.
I’ve added the captcha key into the .env file
GCAPTCHA_SECRET=6Lf5RlwUAAAXXXXXXXXXXXXXXXXXXXXXXXXXX
I want this widget to appear after password confirmation filed, before Register button.
<div class="form-group row mb-0"> <div class="col-md-6 offset-md-4"> <div class="g-recaptcha" data-sitekey="{{ env('GCAPTCHA_SECRET') }}"></div> </div> </div> <div class="form-group row mb-0"> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary"> {{ __('Register') }} </button> </div> </div>
See how it’s appearing in the Laravel register form.
Backend Integration of Google Recaptcha
We are not using, any Captcha packages for Laravel, we build it custom. So let’s create custom validator to validate the Google Captcha. Laravel has the option to create custom validators in your own way.
Create a file called Recapthca.php in the folder app/Validators. You can read more about Laravel custom validators here. I have used https://github.com/guzzle/guzzle to deal HTTP client operations. This custom validator will do all the needful validations for the Google Captcha.
<?php namespace App\Validators; use GuzzleHttp\Client; class Recaptcha { public function validate( $attribute, $value, $parameters, $validator ){ $client = new Client(); $response = $client->post( 'https://www.google.com/recaptcha/api/siteverify', ['form_params'=> [ 'secret'=>env('GCAPTCHA_SECRET'), 'response'=>$value ] ] ); $body = json_decode((string)$response->getBody()); return $body->success; } }
Let’s start with validation in the controller.
protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:6|confirmed', 'g-recaptcha-response' => 'required|recaptcha', ]); }
And the final step will be to register our new validation in AppServiceProvider.php in file app/Providers/AppServiceProvider.php
Import the facade validate
use Illuminate\Support\Facades\Validator;
public function boot() { Validator::extend( 'recaptcha', 'App\\Validators\\Recaptcha@validate' ); }
Hope you’ve had enjoyed other Laravel articles too.
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply