Laravel 8 Google Recaptcha V3 Example

Laravel 8 Google Recaptcha V3 Example

Hi Dev,

Today,I will learn you how to integrate google recaptcha v3 in laravel 8 application. We will talk about laravel 8 google recaptcha implement example tutorial. In this article i will show how to implement google v3 ReCAPTCHA with laravel 8 forms.

This example will give simple way to laravel implement google v3 Recaptcha tutorial, you will learn how to add google v3 Recaptcha with the contact us form in laravel 8.

Here I will give you full example for google recaptcha v3 example in laravel 8. So, let's follow few step to create example of laravel 8 google recaptcha v3 example tutorial.

Step 1 : Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3 : Install josiasmontag/laravel-recaptchav3

In this step, 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

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. Like following:

NOCAPTCHA_SITEKEY=secret_site_key
NOCAPTCHA_SECRET=secret_key 

If you are not register your site with google v3 recaptcha website. So, you can Click Here. And registered your site with filing simple google form.

Then you will get a google client id and secret from the google Recaptcha website.

Step 4 : Create Model and Migration

we are going to create google recaptcha v3 application for contactus. so we have to create migration for "contact_us" table and model using laravel 8 php artisan command, so first fire bellow command:

php artisan make:model ContactUs -m

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create posts table.

<?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');
    }
}

Now you have to run this migration by following command:

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'];
}
Step 5: Create Routes

Here, we need to add route for google recaptcha v3 form. so open your "routes/web.php" file and add following route.

routes/web.php
<?php
use App\Http\Controllers\GoogleV3CaptchaController;

Route::get('google-v3-recaptcha', [GoogleV3CaptchaController::class, 'index']);
Route::post('validate-g-recaptcha', [GoogleV3CaptchaController::class, 'validateGCaptch']);
Step 6: Create Controller

After add route, we need to add method of google recaptcha, first put bellow code on your GoogleController.php file

app/Http/Controllers/GoogleV3CaptchaController.php
<?php
 
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\ContactUs;
use Validator;
use Session;

class GoogleV3CaptchaController extends Controller
{
    public function index()
    {
        return view('google-v3-recaptcha');
    }
 
    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('google-v3-recaptcha')->with('status', 'Google V3 Recaptcha has been validated form');
        }

        return redirect()->back()->withErrors($validator)->withInput();
    }
}
Step 7: Create Blade File

Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:

resources/views/google-v3-recaptcha.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>How to Use Google V3 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>Laravel 8 Contact Us - Adding Google V3 Recaptcha</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:

localhost:8000/google-v3-recaptcha

It will help you....