• Calculating...
  • 5 years ago
  • 6.9K Views
  • Archived This is an Archived post.
    The content within this may not be used or replaced with newer versions.

Integrating Google ReCaptcha in 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.

 

Recaptcha

Google Recaptcha

  1. Create reCAPTCHA for your Domain

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

  1. 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.

  1. 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

<?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'
        ];
    }
}
 
  1. 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');
}
 
  1. 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!";
    }
}
 
  1. 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');
 
  1. Create the index.php View File

The final step is 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.

Share:

Related Post

CRUD Operations In Laravel 8

This tutorial is created to illustrate the basic CRUD (Create , Read, Update, Delete) operation using SQL with Laravel 8. Laravel is one of the fastest-growing frameworks for PHP.

  • 3 years ago

Scheduling Tasks with Cron Job in Laravel 5.8

Cron Job is used to schedule tasks that will be executed every so often. Crontab is a file that contains a list of scripts, By editing the Crontab, You can run the scripts periodically.

  • 5 years ago

Connecting Multiple Databases in Laravel 5.8

This tutorial is created to implement multiple database connections using mysql. Let’s see how to configure multiple database connections in Laravel 5.8.

  • 5 years ago

Clearing Route, View, Config Cache in Laravel 5.8

Sometimes you may face an issue that the changes to the Laravel Project may not update on the web. This occures when the application is served by the cache. In this tutorial, You’ll learn to Clear App

  • 5 years ago

Import, Export from Excel to Database in Laravel 5.8, 5.7, 5

This tutorial is created to Import, Export data from an excel sheet to database in Laravel Framework using maatwebsite/excel package. It provides an easy way to import and export using database model.

  • 5 years ago