Laravel 11 Google Recaptcha V3 Validation Tutorial

Laravel 11 Google Recaptcha V3 Validation Tutorial

In this post, I will show you Laravel 11 Google Recaptcha V3 Validation Tutorial. Google reCAPTCHA v3 is a CAPTCHA-like system that provides security against hackers and scripts or cURL requests. It ensures that a computer user is human. It is the best and most used CAPTCHA system available, where users are only required to click on a checkbox and in some cases select some similar images related to the common question. You Can Learn How to Check If a Value Exists in an Array in PHP?

In this example, we will create a Contact Us form with name, email, and body input fields. we will add Google recaptcha v3 validation. any robot user can not submit the contact us information. so, let’s follow the below steps:

Step for Laravel 11 Google Recaptcha V3 Validation Tutorial?

Let’s see the below steps and make it done.

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel GoogleRecaptcha
cd GoogleRecaptcha

Step 2: Add Google API Key

In this step we need to set google site key and secret key. If you don’t have site key and secret key then you can create from here. First click on this link : Recaptcha Admin

Laravel 11 Google Recaptcha V3 Validation Tutorial

Ok, after successfully register you can get site key and secret key from like bellow preview.

Laravel 11 Google Recaptcha V3 Validation Tutorial

Now open .env file and add this two variable

.env

GOOGLE_RECAPTCHA_KEY=6Lc9hfMfAAAAAMNLm5_2P4jbzVSNWxaF0vgk
GOOGLE_RECAPTCHA_SECRET=6Lc9hfMfAAAAAAdBOKGoz88JVgc5LwMO9

Step 3: Create Routes

In this step, we will create two routes: GET and POST. So let’s add them.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ContactController;
    
Route::get('contact-us', [ContactController::class, 'index']);
Route::post('contact-us', [ContactController::class, 'store'])->name('contact.us.store');

Step 4: Create Validation Rule

In this step, we will create a new “ReCaptcha” validation rule that will check whether the user is real or not using the Google reCAPTCHA v3 API. So let’s run the below command and update the rule validation file.

php artisan make:rule ReCaptcha

app/Rules/ReCaptcha.php

<?php
  
namespace App\Rules;
  
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Http;
  
class ReCaptcha implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $response = Http::get("https://www.google.com/recaptcha/api/siteverify",[
            'secret' => env('GOOGLE_RECAPTCHA_SECRET'),
            'response' => $value
        ]);
  
        if (!($response->json()["success"] ?? false)) {
              $fail('The google recaptcha is required.');
        }
    }
}

Step 5: Create Controller

In this step, we have to create a new controller as ContactController, and we also need to add two methods: index() and store(), to that controller. We will use reCAPTCHA validation on the store method. So let’s update the following code:

app/Http/Controllers/ContactController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Rules\ReCaptcha;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
  
class ContactController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(): View
    {
        return view('contactForm');
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required|digits:10|numeric',
            'subject' => 'required',
            'message' => 'required',
            'g-recaptcha-response' => ['required', new ReCaptcha]
        ]);
  
        $input = $request->all();
  
        /*------------------------------------------
        --------------------------------------------
        Write Code for Store into Database
        --------------------------------------------
        --------------------------------------------*/
  
        return redirect()->back()->with(['success' => 'Contact Form Submit Successfully']);
    }
}

Step 6: Create View File

In the last step, let’s create contactForm.blade.php (resources/views/contactForm.blade.php) to create a form with Google reCAPTCHA v3 and insert the following code:

resources/views/contactForm.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Google ReCaptcha V3 Example - ItSolutionStuff.com</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" />
    <script src="https://code.jquery.com/jquery-3.4.1.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 mt-5 mb-5">
            <div class="col-10 offset-1 mt-5">
                <div class="card">
                    <div class="card-header bg-primary">
                        <h3 class="text-white">Laravel 11 Google ReCaptcha V3 Example - DevScriptSchool.com </h3>
                    </div>
                    <div class="card-body">
                     
                        <form method="POST" action="{{ route('contact.us.store') }}" id="contactUSForm">
                            {{ csrf_field() }}
                              
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <strong>Name:</strong>
                                        <input type="text" name="name" class="form-control" placeholder="Name" value="{{ old('name') }}">
                                        @if ($errors->has('name'))
                                            <span class="text-danger">{{ $errors->first('name') }}</span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <strong>Email:</strong>
                                        <input type="text" name="email" class="form-control" placeholder="Email" value="{{ old('email') }}">
                                        @if ($errors->has('email'))
                                            <span class="text-danger">{{ $errors->first('email') }}</span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <strong>Phone:</strong>
                                        <input type="text" name="phone" class="form-control" placeholder="Phone" value="{{ old('phone') }}">
                                        @if ($errors->has('phone'))
                                            <span class="text-danger">{{ $errors->first('phone') }}</span>
                                        @endif
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <strong>Subject:</strong>
                                        <input type="text" name="subject" class="form-control" placeholder="Subject" value="{{ old('subject') }}">
                                        @if ($errors->has('subject'))
                                            <span class="text-danger">{{ $errors->first('subject') }}</span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <strong>Message:</strong>
                                        <textarea name="message" rows="3" class="form-control">{{ old('message') }}</textarea>
                                        @if ($errors->has('message'))
                                            <span class="text-danger">{{ $errors->first('message') }}</span>
                                        @endif
                                        @if ($errors->has('g-recaptcha-response'))
                                            <span class="text-danger">{{ $errors->first('g-recaptcha-response') }}</span>
                                        @endif
                                    </div>  
                                </div>
                            </div>
                   
                            <div class="form-group text-center">
                                <button class="btn btn-success btn-submit">Submit</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
  
<script type="text/javascript">
    $('#contactUSForm').submit(function(event) {
        event.preventDefault();
    
        grecaptcha.ready(function() {
            grecaptcha.execute("{{ env('GOOGLE_RECAPTCHA_KEY') }}", {action: 'subscribe_newsletter'}).then(function(token) {
                $('#contactUSForm').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
                $('#contactUSForm').unbind('submit').submit();
            });;
        });
    });
</script>
</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/contact-us

Output:

Laravel 11 Google Recaptcha V3 Validation Tutorial

This Post Has One Comment

Leave a Reply