Integrating Google ReCaptcha with Laravel 5.8

reCAPTCHA is a free service from Google. It's a CAPTCHA-like system designed to recognize that the user is human and, at the same time, assist in the digitization of books. It helps to protects your website from spam and abuse.

Note :

If you're running the Laravel Project at your Local Server. It's also acceptable for testing Google reCAPTCHA.

In this tutorial, You'll learn to integrate Google reCAPTCHA in your Laravel Project. Follow the step by step guide to create the application.

Google ReCAPTCHA
  1. Create reCAPTCHA for your Domain

    First, You need to create reCAPTCHA for your domain by logging into Google reCAPTCHA Admin Console.

  2. Set the Keys in .env file

    After creating the account, Obtain the Key and Secret. Add them to the .env file as shown below,

    .env

    RECAPTCHA_KEY='your recaptcha key'
    RECAPTCHA_SECRET='your recaptcha secret'

    You can name the key and secret as you like. I have named them as RECAPTCHA_KEY,RECAPTCHA_SECRET .It is required later in the validation form.

  3. Create the Form Request Validaiton

    Create the Custom Validation Rules using form request validation in by typing the following command,

    php artisan make:request ReCaptchaFormRequest

    The generated class will be stored in in the app/Http/Requests file directory. Open ReCaptchaFormRequest.php from the directory and add the validation rules inside the rules method

    app\Http\Requests\ReCaptchaFormRequest.php

    <?php
    namespace App\Http\Requests;
    use Illuminate\Foundation\Http\FormRequest;
    
    class ReCaptchaFormRequest extends FormRequest
    {
        public function authorize()
        {
            return true;
        }
    
        public function rules()
        {
            return [
                'g-recaptcha-response'=>'required|recaptcha'
            ];
        }
    }
  4. Create the Custom Validation with Guzzle

    If you don’t have Guzzle, Install it by typing the command below at your terminal.

    composer require guzzlehttp/guzzle

    After installing Guzzle, Create a directory as Validation, Inside the Validation folder, Create a PHP file as ReCaptcha.php and add the code below,

    app/Validation/ReCaptcha.php

    <?php namespace App\Validation;
    
    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('RECAPTCHA_SECRET'),
                        'response' => $value
                    ]
                ]
            );
    
            $body = json_decode((string)$response->getBody());
            return $body->success;
        }
    
    }

    The next step is to register Validation in AppServiceProvider's Boot method.

    public function boot()
    {
       Validator::extend('recaptcha','App\\Validation\\ReCaptcha@validate');
    }
  5. Create the Captcha Controller

    Type the following command at your terminal to create CaptchaController.php file in controllers

    php artisan make:controller CaptchaController

    Create two methods as index and captcha in CaptchaController.

    app/Http/Controllers/CaptchaController.php

    <?php
    namespace App\Http\Controllers;
    
    use App\Http\Requests\ReCaptchaFormRequest;
    use Illuminate\Http\Request;
    
    class CaptchaController extends Controller
    {
        public function index()
        {
            return view('index');
        }
    
        public function captcha(ReCaptchaFormRequest $reCaptchaFormRequest)
        {
            return "Done!";
        }
    }
  6. Create the Routes

    In this step, Go to 'routes->web.php' file and add the following code.

    Route::get('/','CaptchaController@index');
    Route::post('/','CaptchaController@captcha');
  7. Create the index.php View File

    And the final step will be to create the index.php file in views directory

    resources/views/index.blade.php

    <!DOCTYPE html>
    <html>
    <head>
        <title>Laravel 5.8 GOOGLE RECAPTCHA - bishrulhaq.com</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <script src='https://www.google.com/recaptcha/api.js'></script>
    </head>
    <body>
    
    <div class="container">
        <div class="row" style="margin-top: 20px;">
            <div class="col-12 ">
                @if (count($errors) > 0)
                    <div class="alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif
            </div>
            <div class="col-12 ">
                <div class="card">
                    <div class="card-body mx-auto">
                        <h3 class="text-center" style="font-weight: bold;padding-bottom: 10px;">GOOGLE ReCAPTCHA</h3>
                        <form class="form-horizontal" action="" method="post">
                            {!! csrf_field() !!}
                            <div class="form-group">
                                <div class="col-md-12">
                                    <div class="g-recaptcha " data-sitekey="{{env('RECAPTCHA_KEY')}}"></div>
                                </div>
                            </div>
                            <div class="form-group">
                                <button type="submit" name="submit" class="btn btn-success">Submit</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    </body>
    </html>
    
    

    Type the following command in your terminal to run the project.

    php artisan serve

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.