Google Recaptcha V3 Example Tutorial in Laravel 8

Hello buddies,

How are you guys? Today I am goin to show you how to add google recaptcha in your laravel web application. Let’s look at an example of integrating recaptcha in laravel application. This article will go over how to implement google recaptcha in Laravel 8. I’ll teach you how to use Google’s v3 ReCAPTCHA with Laravel 8 forms in this article. This tutorial will show you how to use recaptcha in laravel.

Create Laravel project

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

Set Database Configuration properties

Go to the .env file and set you Database name, Database username and password.

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

Install Laravel  josiasmontag/laravel-recaptchav3

We need josiasmontag/laravel-recaptchav3 package. you can install google v3 recaptcha validation package in laravel 8 google v3 recaptcha validation app. So let’s open terminal and run bellow command:

composer require josiasmontag/laravel-recaptchav3 
Github-link: josiasmontag/laravel-recaptchav3

After install above package you can add providers and aliases in config file. So lets run bellow command to publish the config file:

php artisan vendor:publish --provider="Lunaweb\RecaptchaV3\Providers\RecaptchaV3ServiceProvider"

Then add the site key and secret key on .env file provided by google recaptcha website.

NOCAPTCHA_SITEKEY=your_secret_site_key 
NOCAPTCHA_SECRET=your_secret_key 

Create Model and Migration

We  are going to create google recaptcha v3 application for contact-us page in my laravel app. So run bellow command:

php artisan make:model ContactUs -m

Add the following code in your database/migrations file

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateContactUsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contact_us', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('subject');
            $table->text('message');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contact_us');
    }
}

Migrate

php artisan migrate

Now you can add all table column in fillable So let’s open model file put bellow code.

app/Models/ContactUs.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ContactUs extends Model
{
    use HasFactory;
    
    protected $table = 'contact_us';
    protected $fillable = ['name', 'email','subject','message'];
}

Create Routes

Read Also: Laravel 8 REST API Authentication with Sanctum

Go to .env file and create the following routes respectively

routes/web.php

Route::get('contact-us', [GoogleV3CaptchaController::class, 'index']);
Route::post('validate-g-recaptcha', [GoogleV3CaptchaController::class, 'validateGCaptch']);

Create Controller

Now it’s time to create our controller, run bellow command:

php artisan make:controller recaptcha\GoogleV3CaptchaController

app/Http/Controllers/recaptcha/GoogleV3CaptchaController.php

<?php

namespace App\Http\Controllers\recaptcha;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ContactUs;
use Validator;
use Session;


class GoogleV3CaptchaController extends Controller
{
    public function index()
    {
        return view('contact');
    }
 
    public function validateGCaptch(Request $request)
    {
        $input = $request->all();

        $validator = Validator::make($input,[
            'name' => 'required',
            'email' => 'required',
            'subject' => 'required',
            'message' => 'required',
            'g-recaptcha-response' => 'required',
        ]);

        if ($validator->passes()){
            ContactUs::create($input);
            return redirect('contact-us')->with('status', 'Google V3 Recaptcha has been validated form');
        }

        return redirect()->back()->withErrors($validator)->withInput();
    }
}

Create Blade File(contact)

We need to add a blade view so first create new file contact.blade.php file and put bellow code:

resources/views/contact.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Google Recaptcha Validation In Laravel 8 Form</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-4">
        @if(session('status'))
            <div class="alert alert-success">
                {{ session('status') }}
            </div>
        @endif
        <div class="card">
            <div class="card-header text-center font-weight-bold">
                <h2>Contact Us</h2>
            </div>
            <div class="card-body">
                <form name="g-v3-recaptcha-contact-us" id="g-v3-recaptcha-contact-us" method="post" action="{{url('validate-g-recaptcha')}}">
                    @csrf
                    <div class="form-group">
                        <label for="exampleInputEmail1">Name</label>
                        <input type="text" id="name" name="name" class="@error('name') is-invalid @enderror form-control">
                        @error('name')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>          
                    <div class="form-group">
                        <label for="exampleInputEmail1">Email</label>
                        <input type="email" id="email" name="email" class="@error('email') is-invalid @enderror form-control">
                        @error('email')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>           
                    <div class="form-group">
                        <label for="exampleInputEmail1">Subject</label>
                        <input type="text" id="subject" name="subject" class="@error('subject') is-invalid @enderror form-control">
                        @error('subject')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>      
                    <div class="form-group">
                        <label for="exampleInputEmail1">Message</label>
                        <textarea name="message" class="@error('description') is-invalid @enderror form-control"></textarea>
                        @error('message')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="form-group">
                        <input type="hidden" name="g-recaptcha-response" id="recaptcha">
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>    
    <script src="https://www.google.com/recaptcha/api.js?render={{ config('services.recaptcha.sitekey') }}"></script>
    <script>
             grecaptcha.ready(function() {
                 grecaptcha.execute('{{ config('services.recaptcha.sitekey') }}', {action: 'contact'}).then(function(token) {
                    if (token) {
                      document.getElementById('recaptcha').value = token;
                    }
                 });
             });
    </script>
    <!-- <script src="https://www.google.com/recaptcha/api.js?render={{ config('services.recaptcha.sitekey') }}"></script> -->
    
</body>
</html>

Now we are ready to run our google recaptcha v3 example with laravel 8 so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/contact-us

It will help you….