LARAVEL Tutorial


Laravel 7 Google Recaptcha V2 Validation Example


When you are working in Laravel web application. So many times you need to protect the form of Laravel.

Google v2 Recaptcha protects your web applications from spammers. It validates the data of your web application form. Only after this, other activities can be done.

If a user has been spammed in your web application contact form, etc. So you can stop the spammer using the google v2 Recaptcha Package.

In this laravel tutorial, you will learn how to implement or integrate google v2 recaptch with form in laravel web applications.

Laravel Google Recaptcha v2 Example

  • Install Laravel Application
  • Configure Database Detail
  • Run Migration
  • Install Google Captcha Package
  • Get Google ReCaptcha Secret
  • Create Routes
  • Generate Controller By Artisan
  • Create Blade View
  • Start Development Server

Install Laravel Application

First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:

composer create-project laravel/laravel laravel-google-recaptcha –-prefer-dist

If you want to install a specific version of laravel, you can follow the following tutorial

https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer

Configure Database Detail

After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=root

Run Migration

Before you will run php artisan migrate command. Go to app/providers/AppServiceProvider.php and update the below code :

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

Next, go to command prompt and run the following command:

php artisan migrate

OR

php artisan migrate:fresh

This php artisan migrate command creates a table in your database.

Install Google Captcha Package

Next, we need to install the laravel google Recaptcha package. So use the following command to install the laravel google Recaptcha package.

composer require anhskohbo/no-captcha

After that, you need to register laravel Google Captcha Packages. So open config/app.php file and add service provider and alias.

'providers' => [
 
 
 Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class
 
 
 ],
 
 
 'aliases' => [
 
 
 'NoCaptcha' => Anhskohbo\NoCaptcha\Facades\NoCaptcha::class,
 
 
 ]

Get Google ReCaptcha Secret

Next, you need to get google Recaptcha site_key and secret_key from google Recaptcha site. If you have already site_key and secret_key, so you need to put the .env file. If you don't know where we will get secret_key and secret_site click below the link and create your own secret credentials.  Recaptcha new site registration

After that, we will set the google captcha secret in .env files, let's open .env file and add this credentials here

NOCAPTCHA_SITEKEY=secret_site_key
NOCAPTCHA_SECRET=secret_key

Create Routes

Next step, go to routes/web.php file and update the following routes into your file:

 Route::get('form', 'GoogleReCaptchaController@index');
 Route::post('store', 'GoogleReCaptchaController@store');

Generate Controller By Artisan

Now, you need to generate or create a controller file using php artisan command, so use the php artisan make:controller command and generate/create a new controller file:

php artisan make:controller GoogleReCaptchaController

We will create two methods in this controller file. This method will also show  Recaptcha form and store from data into the database in laravel web applications.

After that, go to App/Http/Controllers/ directory and find the created GoogleReCaptchaController file and update the following code into your file:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator,Redirect,Response;
use App\User;

class GoogleReCaptchaController extends Controller
{
    public function index()
    {
       return view('recaptch-form');
    }  
    public function store(Request $request)
    {
        request()->validate([
        'name' => 'required',
        'email' => 'required',
        'mobile_number' => 'required',
        'g-recaptcha-response' => 'required|captcha',
        ]);

        dd('successfully validate');
    }
}

Create Blade Views

Next, you need to create a blade views file, so go resource/views directory and create the following blade views file.

You need to include the following typehead js JavaScript library in the form below.

  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>

Go to resource/views/ then create a new file name search-page.blade.php and update the following code:

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="csrf-token" content="{{ csrf_token() }}">

  <title>Laravel Google Recatpcha Verification - w3alert.com</title>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
 
  <style>
   .error{ color:red; } 
  </style>
</head>

<body>

<div class="container">

    @if ($message = Session::get('success'))
    <div class="alert alert-success alert-block">
        <button type="button" class="close" data-dismiss="alert">×</button>
          <strong>{{ $message }}</strong>
    </div>
    <br>
    @endif
  
    <form id="captcha-form" method="post" action="{{url('store')}}">
      @csrf
      <div class="form-group">
        <label for="formGroupExampleInput">Name</label>
        <input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
        <span class="text-danger">{{ $errors->first('name') }}</span>
      </div>

      <div class="form-group">
        <label for="email">Email Id</label>
        <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
        <span class="text-danger">{{ $errors->first('email') }}</span>
      </div>      

      <div class="form-group">
        <label for="captcha">Captcha</label>
          {!! NoCaptcha::renderJs() !!}
          {!! NoCaptcha::display() !!}
        <span class="text-danger">{{ $errors->first('g-recaptcha-response') }}</span>
      </div>
      <div class="form-group">
       <button type="submit" class="btn btn-success">Submit</button>
      </div>
    </form>
</div>
</div>
</div>

</body>
</html>

Start development server

You can use the following command artisan command to start the development server:

php artisan serve

The final step, go to your browser and type the below-given URL into your browser:

http://localhost:8000/form

OR

http://localhost/laravel-google-recaptcha/public/form