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
How to Install Jenkins on Ubuntu
How to Install Jenkins on Ubun...

In today's fast-paced software development landscape, I've understood the significance of continuous integration...

Read More

Aug-07-2023

Laravel 8 CRUD Operation Example
Laravel 8 CRUD Operation Examp...

In this article, we will see the laravel 8 crud operation. As you know Laravel 8 has already been officially released an...

Read More

Sep-16-2020

Bootstrap Session Timeout Example In Laravel
Bootstrap Session Timeout Exam...

In this tutorial, I will show you a session timeout example in laravel. After a set amount of idle time, the bootstrap w...

Read More

Jun-05-2020

How to Get Random Record in Laravel 10
How to Get Random Record in La...

Here you will learn how to get random records from DB in laravel using the inRandomOrder() method. Explore an...

Read More

Nov-10-2023