How To Use Google Recaptcha V2 In Laravel 9

Websolutionstuff | Jun-14-2022 | Categories : Laravel PHP

In this article, we will see how to use google ReCaptcha v2 in laravel 9. Google ReCaptcha is used for advanced risk analysis techniques to show humans and bots apart. that defends your site from spam and abuse. And it makes your site more secure.

So, let's see how to use google ReCaptcha v2 in laravel 9, ReCaptcha v2 laravel 9, how to add google ReCaptcha in laravel 9, google ReCaptcha in laravel 9, laravel 9 google ReCaptcha v2 example, google API console developer, Google API integration in laravel 9.

Step 1: Install Laravel 9

In this step, we will install laravel 9 using the below command.

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

 

 

Step 2: Add Google API key

Now, we need to add Google Site Key and Secret Key in the .env file, if you don't have these keys then you need to create them from google's website

Click here to create a new site key and secret key: Generate Recaptcha

Recaptcha

key

After that open the .env file and add these keys.

GOOGLE_RECAPTCHA_KEY=XXXXXX
GOOGLE_RECAPTCHA_SECRET=XXXXX

 

 

Step 3: Add Route

We need to add a route for the details view file.

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
   
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
    
Route::get('contact-us', [UserController::class, 'index']);
Route::post('contact-us', [UserController::class, 'store'])->name('contact.us.store');

 

Step 4: Create Validation Rule

In this step, we will create rules for ReCaptcha validation that will check whether the user is real or not using google ReCaptcha v2 API. 

php artisan make:rule ReCaptcha

app/Rules/ReCaptcha.php

<?php
  
namespace App\Rules;
  
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Http;
  
class ReCaptcha implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
          
    }
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $response = Http::get("https://www.google.com/recaptcha/api/siteverify",[
            'secret' => env('GOOGLE_RECAPTCHA_SECRET'),
            'response' => $value
        ]);
          
        return $response->json()["success"];
    }
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The google ReCaptcha is required.';
    }
}

 

 

Step 5: Create Controller

Now create a controller on this path app\Http\Controllers\UserController.php and add the below command. And also, we put validation for fields and captcha, if anyone is failed then it will display error messages.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Rules\ReCaptcha;

class UserController extends Controller
{
    
    public function create()
    {
        return view('users.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'g-recaptcha-response' => ['required', new ReCaptcha]
        ]);

        User::create($request->all());
   
        return "Successfully Created";
    }
}

 

Step 6: Create Blade File 

Now, create.blade.php file in this path resources\views\create.blade.php and add the below html code.

<html>
<head>
   <title>How To Use Google Recaptcha V2 In Laravel 9 - websolutionstuff.com</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
   <script src="https://www.google.com/recaptcha/api.js?render={{ env('GOOGLE_RECAPTCHA_KEY') }}"></script>
</head>
<body>

   <div class="container">
      <div class="row" style="margin-top: 10px;">
         <div class="col-lg-12 margin-tb">
            <div class="text-center">
               <h2>Create New User</h2>
            </div>
         </div>
      </div>

      @if ($errors->any())
      <div class="alert alert-danger">
         <strong>Error!</strong> <br>
         <ul>
            @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
            @endforeach
         </ul>
      </div>
      @endif

      <form action="{{ route('users.store') }}" method="POST" id="contact_us_form">
         @csrf
         <div style="margin-left: 400px;">
            <div class="row">
               <div class="col-xs-12 col-sm-12 col-md-6">
                  <div class="form-group">
                     <strong>Name:</strong>
                     <input type="text" name="name" class="form-control" placeholder="Name">
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="col-xs-12 col-sm-12 col-md-6">
                  <div class="form-group">
                     <strong>Email:</strong>
                     <input type="email" name="email" class="form-control" placeholder="Email">
                  </div>
               </div>
            </div>            
            <div class="row">
               <div class="col-xs-12 col-sm-12 col-md-12 text-left">
                  <button type="submit" class="btn btn-primary">Submit</button>
               </div>
            </div>
         </div>
      </form>
   </div>
</body>
<script type="text/javascript">
    $('#contact_us_form').submit(function(event) {
        event.preventDefault();
    
        grecaptcha.ready(function() {
            grecaptcha.execute("{{ env('GOOGLE_RECAPTCHA_KEY') }}", {action: 'submit'}).then(function(token) {
                $('#contact_us_form').prepend('<input type="hidden" name="token" value="' + token + '">');
                $('#contact_us_form').unbind('submit').submit();
            });;
        });
    });
</script>
</html>

 

 

Output:

recaptcha_output


You might also like:

Recommended Post
Featured Post
Routing - Laravel 7/8 Routing Example
Routing - Laravel 7/8 Routing...

In this article, we will give you information about the basic route, named route, and advanced route in laravel 7 and la...

Read More

Nov-01-2020

Queen Elizabeth II Portrait Using CSS
Queen Elizabeth II Portrait Us...

In this article, we will see Queen Elizabeth II portrait using CSS. Elizabeth II was Queen of the United Kingd...

Read More

Sep-11-2022

How To Import Export Excel & CSV File In Laravel 10
How To Import Export Excel & C...

In this article, we will see how to import and export Excel & CSV files in laravel 10. Here, we will learn about lar...

Read More

Mar-08-2023

How To Create Dynamic XML Sitemap In Laravel 9
How To Create Dynamic XML Site...

In this article, we will see how to create a dynamic XML sitemap in laravel 9. As we know sitemap is a very im...

Read More

Jun-08-2022