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 Validate Password And Confirm Password In React JS
How To Validate Password And C...

In this article, we will see how to validate password and confirm password in react js. Sometimes we need to add th...

Read More

Sep-14-2022

Laravel 9 One To Many Polymorphic Relationship
Laravel 9 One To Many Polymorp...

In this article, we will see laravel 9 one to many polymorphic relationship. A one-to-many polymorphic relation is...

Read More

Apr-05-2022

How To Validate Username And Password In React JS
How To Validate Username And P...

In this article, we will see how to validate username and password in react js. In this example, we will validate t...

Read More

Sep-13-2022

Laravel 9 One To Many Relationship Example
Laravel 9 One To Many Relation...

In this article, we will see laravel 9 one to many relationship example. Also, you can use one to many relationships in...

Read More

Apr-02-2022