Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







Google reCAPTCHA Integration In PHP Laravel Forms


Share On     Share On WhatsApp     Share On LinkedIn


Hello there! In this article you will learn how to implement Google ReCaptcha in PHP Laravel forms.


WHY Google ReCaptcha?
One of the basic question that will arise is why Google ReCaptcha? It's mainly because of security concerns. If you have contact form or any other form you don't want to get spammed with junk data. One way to fight against this is Google ReCaptcha.
Google reCAPTCHA | PHP Laravel Example

Google reCAPTCHA | PHP Laravel Example


Prerequisites


You have fresh installation of Laravel with default Authentication setup. If you don't know how to setup the Basic Auth then I will come up with one more article soon where you will learn how to achieve it.


Step 1 - Setup Google ReCaptcha Authentication Keys


Please use the following URL to setup your Google ReCaptcha. You have to login with your registered account. You will be able to see the following new site form like the one shown in the following image.


Google Recaptcha


Google reCAPTCHA Form | After Sign In

Google reCAPTCHA Form | After Sign In



As you see you have to fill the following from the above Image


Label - Name To Identify

Name of your website or something you can easily identify for which site you created it for.

reCAPTCHA type - Version Of reCAPTCHA

Your free to select V3 or V2 as per your needs. I am selecting

reCAPTCHA V2 -> "I'm not a robot" tick box

Domains - Domain Name (Website Name)

This is a must, if you don't specify the domain name then anyone with your keys can use it for free and you will be charged for it.

Accept Terms - Obviously if you don't you cant create reCaptcha auth keys.


Send Alert To Owners - Please check mark this


Then submit. You will RECAPTCHA SITE KEY & SECRET KEY.



Step 2 - Copy ReCaptcha Keys To .env File


Now you have ReCaptcha Keys generated add those to .env file as below. Observe RECAPTCHA_SITE_KEY & RECAPTCHA_SECRET_KEY.


RECAPTCHA_SITE_KEY=6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI

RECAPTCHA_SECRET_KEY=6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe


NOTE: The above are Google Test Keys make sure not to use in your production

Step 3 - Add reCAPTCHA In View Pages


I am having contact form as you can see in the following URL of my website Contact Form. To get that kind of google recaptcha you have to add this in your blade template.


<!-- Add this javascript before the end of your /body tag !-->

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



<div class="row form-group">

  <div class="col-md-12">
       <!-- As you can see the RECAPTCHA_SITE_KEY here we are using it from .env file -->
       <!-- We dont have any name here as by default google will include g-recaptcha-response name for this field -->
       <div class="g-recaptcha" data-sitekey="{{ env('RECAPTCHA_SITE_KEY') }}"></div>

       @error('g-recaptcha-response')

           <div class="text-danger"><em>{{ $message }}</em></div>

       @enderror

  </div>

</div>


Now you will be able to see the following image, which means you can configured everything fine till now. Hey buddy good going.


Google reCAPTCHA Image After Laravel Blade Integration

Google reCAPTCHA Image After Laravel Blade Integration



Step 4 - Google reCaptcha Library For Server Side Validation


One we have show then google recaptcha it doesnt mean its all done and you can sit back and relax. The captcha has to be verified from google server to know it the user selected recaptcha was verified or not.


We can easily do this by using google library using composer. For more details see this URL on GIT repo Google Recaptcha


composer require google/recaptcha


This will download the necessary package via which we can validate the user sent recaptcha code.



Step 5 - Server Side Validation


Now when user fills the form and submit we need to do server side validation of the form details as shown in the following code


NOTE: I have used the custom validation rules in the following code ie GoogleRecaptcha() make sure to check the code in step 6


/** This is my custom validation in laravel */
use App\Rules\GoogleRecaptcha;

public function store(){
    request()->validate([
        /** Other fields validated here */
        'email'                 => 'required|email',
        'description'           => 'required',
        /** See this line this is where google recaptcha will be validated */
        'g-recaptcha-response'  => new GoogleRecaptcha(),
    ]);
    /** After successful validation store the data in your database */
    /** You may want to send your self notification via email, sms */
}


If the google is not able to validate the user submitted recaptcha then it will throw error and will be sent back to user form with g-recaptcha-response. Where the following error block will handle to display the appropriate error message

As seen in Step 3


 @error('g-recaptcha-response')

    <div class="text-danger"><em>{{ $message }}</em></div>

@enderror



Step 6 - Custom Validation Code For Google Verification


The following is full code for custom validation rule in Laravel


NOTE: If you want to learn how to create custom validation rules in Laravel then please follow my another article where I have given in depth details on it How To Create Custom Validation Rules In PHP Laravel (Using Artisan Command)


<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use ReCaptcha\ReCaptcha;

class GoogleRecaptcha implements Rule
{
    /** REMOVED CONSTRUCTOR */

    public function passes($attribute, $value)
    {
        $recaptcha  = new ReCaptcha(env('RECAPTCHA_SECRET_KEY'));
        $response   = $recaptcha->verify($value, $_SERVER['REMOTE_ADDR']);
        return $response->isSuccess();
    }

    public function message()
    {
        return 'Please verify recaptcha.';
    }
}


Tada! You not finished the setup of your google recaptcha.


Step 7 - Testing


Now submit your form and check if everything works fine for you. If you leave recaptcha in form field empty then required error will be shown.


Conclusion


Remember
After implementing this you might feel that you are very safe, then my friend you have miss understood the cruel world. This is not be your final solution to your security issues. There might be libraries that may bypass this, but this acts as added bonus to overcome few of them.

You might be interested to read the following articles to get good understanding on the concepts what I have used here.

How To Create Custom Validation Rules In PHP Laravel (Using Artisan Command)




Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing