Laravel 10 Google Recaptcha V3 Validation Tutorial

Laravel 10 Google Recaptcha V3 Validation Tutorial

If you are creating any forms in the Laravel web application and you want that no one should do spam, no robot entry, and no hacking through that form. So for this you can use Google’s recaptcha v3. In this tutorial, you will learn how to integrate Google v3 ReCAPTCHA validation with Laravel 10 forms.

Laravel 10 Google Recaptcha V3 Validation Tutorial

By using the following steps, you can integrate google reCaptcha v3 in laravel 10 apps with validation:

  • Step 1 – Create New Laravel 10 Project
  • Step 2 – Setup Database to Laravel App
  • Step 3 – Setup Google V3 Recaptcha Package
  • Step 4 – Create Model & Migration
  • Step 5 – Define Routes
  • Step 6 – Create Controller
  • Step 7 – Create Blade File
  • Step 8 – Start Development Server
  • Step 9 – Run This App On Browser

Step 1 – Create New Laravel 10 Project

First of all, start your terminal to download or install Laravel 10 new setup. Run the following commands in it to install the new Laravel 10 app on your system:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install Laravel 10 latest application using the following command:

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

Step 2 – Setup Database to Laravel App

In this step, Configure your database with your apps. So, visit your app root directory and find .env file. Then configure database details as follows:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Setup Google V3 Recaptcha Package

In step 3, open command prompt and navigate to your project by using the following command:

cd / LaravelGoogleV3Recaptcha

Then run the following command to install google v3 recaptcha validation package in Laravel 10 google v3 recaptcha validation app:

composer require josiasmontag/laravel-recaptchav3

After successfully installed this package. Optionally, you can 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:

RECAPTCHAV3_SITEKEY=secret_site_key
RECAPTCHAV3_SECRET=secret_key 

If you are not register your site with google v3 recaptcha website. So, you can visit this link. 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 & Migration

In step 4, create model and migration file for contact us form by using the following command:

php artisan make:model ContactUs -m

The above command will create two files into your Laravel 10 google v3 recaptcha validation application, which is located inside the following locations:

  • LaravelGoogleV3Recaptcha/app/Models/ContactUs.php
  • LaravelGoogleV3Recaptcha/database/migrations/create_contact_us_table.php

So, find create_contact_us_table.php file inside LaravelGoogleV3Recaptcha/database/migrations/ directory. Then open create_contact_us.php file and add the following code into function up() on this file:

    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();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 5 – Define Routes

In step 5, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

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

In step 6, create Google v3 recaptcha controller by using the following command:

php artisan make:controller GoogleV3CaptchaController

The above command will create GoogleV3CaptchaController.php file, which is located inside LaravelGoogleV3Recaptcha/app/Http/Controllers/ directory.

The following laravel validation rules will validate google recaptcha form data before save into database in laravel:

        $validatedData = $request->validate([
            'name' => 'required',
            'email' => 'required',
            'subject' => 'required',
            'message' => 'required',
            'g-recaptcha-response' => 'required|recaptchav3:contact-us,0.5'

        ]);

So open GoogleV3CaptchaController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ContactUs;


class GoogleV3CaptchaController extends Controller
{
    public function index()
    {
        return view('google-v3-recaptcha');
    }

    public function validateGCaptch(Request $request)
    {
        
        $validatedData = $request->validate([
            'name' => 'required',
            'email' => 'required',
            'subject' => 'required',
            'message' => 'required',
            'g-recaptcha-response' => 'required|recaptchav3:contact-us,0.5'

        ]);


        $save = new ContactUs;

        $save->name = $request->name;
        $save->email = $request->email;
        $save->subject = $request->subject;
        $save->message = $request->message;

        $save->save();

        return redirect('google-v3-recaptcha')->with('status', 'Google V3 Recaptcha has been validated form');

    }
}

Step 7 – Create Blade File

In step 7, create new blade view file that named google-v3-recaptcha.blade.php inside resources/views directory for display contact us form with google v3 recaptcha validation in laravel.

One more thing for use google v3 recaptcha with laravel forms, you need to add the following code on laravel form:

{!! RecaptchaV3::initJs() !!}

{!! RecaptchaV3::field('contact-us') !!}

Don’t worry we have already added the validation error message display code along with each form fields and google v3 recaptcha validation code.

So, you can add the following php and html form code into google-v3-recaptcha.blade.php:

<!DOCTYPE html>
<html>
<head>
	<title>How to Use Google V3 Recaptcha Validation In Laravel 10 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 10 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">Description</label>
          <textarea name="description" class="@error('description') is-invalid @enderror form-control"></textarea>
          @error('description')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
        </div>

      <div class="form-group">
          {!! RecaptchaV3::initJs() !!}

          {!! RecaptchaV3::field('contact-us') !!}
   
          @error('g-recaptcha-response')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
      </div>

        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    </div>
  </div>
</div>	
</body>
</html>

Step 8 – Start Development Server

In step 8, open your command prompt again and run the following command to start development server for your Laravel 10 google v3 recaptcha form validation application:

php artisan serve

Step 9 – Run Laravel 10 Google V3 Recaptcha Validation App On Browser

In step 9, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/google-v3-recaptcha

Laravel google v3 recaptcha form validation apps looks like in following image:

Recommended Laravel Posts

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *