codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Simple integration Google reCAPTCHA v2 with Laravel in details

Introduction

One week ago I started to migrate one of my project to the Laravel framework. And Google reCAPTCHA v2 validation was the first problem I faced. After solving this problem I decided for myself how I would do that for the next time in all my projects (if it will be necessary).

For this purpose let’s create a simple small project that just will allow us to send a feedback. In this project we will use Bootstrap 4 css framework, Vue.js and axios library for AJAX requests. So, in the end we must have feedback form that send AJAX request to the server where we validate data and if all right create new record in the database. So simple, let’s do it.

Preparation

First of all, we need such parameters for Google reCAPTCHA as site key and secret key. In our case we will use testing parameters, so just add this two lines to your .env file:

GOOGLE_RECAPTCHA_KEY=6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
GOOGLE_RECAPTCHA_SECRET=6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

Read more about how to verify user’s response from the application’s backend.

For verifying user’s response we need to send POST request to this url: https://www.google.com/recaptcha/api/siteverify. For that we will use Client class from guzzlehttp package.

So just run this command in project folder for adding this package to your composer.json file:

composer require guzzlehttp/guzzle

The next step is to create Feedback model, Feedback controller and migration for feedback model:

php artisan make:model Feedback -mc

Create Feedback request class:

php artisan make:request FeedbackRequest

And the main thing is creating rule for reCAPTCHA validation:

php artisan make:rule ValidRecaptcha

WARNING!

If you use MariaDB there is can be a problem to work with DBMS via artisan command. In this case all that you need is using this in AppServiceProvider:

use Illuminate\Support\Facades\Schema;public function boot()
{
Schema::defaultStringLength(191);
}

Routes

On the main page we will see feedback form. And for the comfort let’s create page with all out feedback messages (here we can delete a specific feedback, if we want to).

Route::get('/', 'FeedbackController@create');
Route::get('/feedback', 'FeedbackController@index');
Route::post('/feedback/create', 'FeedbackController@store');
Route::get('/feedback/delete/{id}', 'FeedbackController@destroy');

Frontend

Views

I think that we can skip the main layout file app.blade.php and look only at pages: create.blade.php and index.blade.php.

index.blade.php

As you can see there are no interesting things in here.

create.blade.php

The main thing here for put article is this line:

<div class="g-recaptcha" id="feedback-recaptcha" data-sitekey="{{ env('GOOGLE_RECAPTCHA_KEY')  }}"></div>

But don’t forget in main layout file add this line:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Styles

/resources/assets/sass/app.scss

// Fonts
@import url('https://fonts.googleapis.com/css?family=Nunito');

// Variables
@import 'variables';

// Bootstrap
@import '~bootstrap/scss/bootstrap';

.navbar {
background-color: #e3f2fd;
}

.container {
margin-top: 20px;
}

.btn-feedback-block {
margin-top: 15px;
}

JavaScript

/resources/assets/js/app.js

In this file you can see, that here we use SweetAlert2 library.

In this line we get value of our reCAPTCHA input and add this value to our FormData object:

form_data.append('g-recaptcha-response', $("#g-recaptcha-response").val());

Backend

Database

Our table structure in create_feedback_table.php:

Model

Model is empty:

class Feedback extends Model
{
//
}

Controller

Here we see that we get FeedbackRequest as a parameter in the store() method. So after that our request validates in the FeedbackRequest.php file.

Request

Change return value of the authorize() method to true:

public function authorize()
{
return true;
}

Use rule ValidRecaptcha in this file:

use App\Rules\ValidRecaptcha;

Create validation rules:

public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'message' => 'required',
'g-recaptcha-response' => ['required', new ValidRecaptcha]
];
}

Set message for our g-recaptcha-response required field:

public function messages()
{
return [
'g-recaptcha-response.required' => 'Please ensure that you are a human!'
];
}

Now let’s create new rule for reCAPTCHA validation.

Rule

Use Client class from GuzzleHttp:

use GuzzleHttp\Client;

Create new object with base_uri:

$client = new Client([
'base_uri' => 'https://google.com/recaptcha/api/'
]);

Send post request with secret from our .env file and with the value from out g-recaptcha-response field:

$response = $client->post('siteverify', [
'query' => [
'secret' => env('GOOGLE_RECAPTCHA_SECRET'),
'response' => $value
]
]);

Get response body and return result:

return json_decode($response->getBody())->success;

If the passes() method return false we will get the next message:

public function message()
{
return 'ReCaptcha verification failed.';
}

Result

Feeback form

Feedback form

Feedback messages list

Feedback messages list

Data is invalid

Data is invalid 1
Data is invalid 2

Feedback successfully send

Feedback successfully send

Conclusion

The main point of this article is figure out how we can validate Google reCAPTCHA in our laravel application. It’s all about server side validation and right now this solution seem the best practice for me.

P.S. The source code available on GitHub. If you have any questions or suggestions write it on the comments. Thank you for the reading!

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

No responses yet

Write a response