Laravel 11 Google v2 ReCAPTCHA Form Validation

Laravel 11 google ReCAPTCHA v2 form validation; Through this tutorial, i am going to show you how to integrate google ReCAPTCHA v2 to validate form in Laravel 11 apps.

In this post, i will use google recaptcha package that name anhskohbo/no-captcha. And i will create contact us form. And will integrate google v2 recaptcha with contact us form in laravel version.

How to Use Google Recaptcha in Laravel 11 Apps

Use the below given steps to add google reCaptcha security in Laravel 11 forms:

  • Step 1 – Install Laravel 11 Application
  • Step 2 – Configuring Database using Env File
  • Step 3 – Install Google Recaptcha Package (anhskohbo/no-captcha)
  • Step 4 – Create Model & Migration File For Contact Us Form
  • Step 5 – Create Routes
  • Step 6 – Creating Controller
  • Step 7 – Create Blade File For Contact Us Form
  • Step 8 – Start Development Server
  • Step 9 – Run Laravel 11 Google V2 Recaptcha Validation App On Browser

Step 1 – Install Laravel 11 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel latest application using the following command:

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

Step 2 – Configuring Database using Env File

In step 2, open your downloaded Laravel 11 app into any text editor. Then find .env file and configure database detail like following:

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 – Install Google Recaptcha Package (anhskohbo/no-captcha)

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

cd / LaravelGoogleV2

Then run the following command to install google v2 recaptcha validation package in laravel google v2 recaptcha validation app:

composer require anhskohbo/no-captcha

After successfully installed this package. Then register this package providers and alies on app.php file, which is located inside config directory:

config/app.php
 
 
 'providers' => [
 
 
 Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class
 
 
 ],
 
 
 'aliases' => [
 
 
 'NoCaptcha' => Anhskohbo\NoCaptcha\Facades\NoCaptcha::class,
 
 
 ]  

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 v2/v3 recaptcha website. So, you can visit this link. And registered your site with filing simple google form.

The Google v2/v3 Recaptcha registration form will look like in following image:

Step 4 – Create Model & Migration File For Contact Us Form

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 google v2 recaptcha validation application, which is located inside the following locations:

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

So, find create_contact_us_table.php file inside LaravelGoogleV2/database/migrations/ directory. Then open this 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 – Create Routes

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

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\GoogleV2Controller;


/*
|--------------------------------------------------------------------------
| 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('/', function () {
    return view('welcome');
});

Route::get('google-v2-contact-us', [GoogleV2Controller::class, 'index']);
Route::post('validate-store', [GoogleV2Controller::class, 'store']);

Step 6 – Creating Controller

In step 6, create form controller by using the following command:

php artisan make:controller GoogleV2Controller

The above command will create GoogleV2Controller.php file, which is located inside LaravelGoogleV2/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|captcha',
        ]);

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

<?php

namespace App\Http\Controllers;

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


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

    public function store(Request $request)
    {
        
        $validatedData = $request->validate([
            'name' => 'required',
            'email' => 'required',
            'subject' => 'required',
            'message' => 'required',
            'g-recaptcha-response' => 'required|captcha',
        ]);


        $save = new ContactUs;

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

        $save->save();

        return redirect('google-v2-contact-us')->with('status', 'Google V2 Recaptcha has been validated form');

    }
}

Step 7 – Create Blade File For Contact Us Form

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

The following code display error message in laravel forms. So do not forget to add the following code along laravel forms fields:

          @error('title')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror

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

      <div class="form-group">
        <label for="captcha">Captcha</label>
          {!! NoCaptcha::renderJs() !!}
          {!! NoCaptcha::display() !!}
          @error('g-recaptcha-response')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
      </div>

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

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

<!DOCTYPE html>
<html>
<head>
	<title>How to Use Google V2 Recaptcha Validation In Laravel 11 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 11 Google V2 Recaptcha Form Validation Example</h2>
    </div>
    <div class="card-body">
      <form name="google-recaptcha-contact-us" id="google-recaptcha-contact-us" method="post" action="{{url('validate-store')}}">
       @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">
        <label for="captcha">Captcha</label>
          {!! NoCaptcha::renderJs() !!}
          {!! NoCaptcha::display() !!}
          @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 11 google v2 recaptcha form validation application:

php artisan serve

Step 9 – Run Laravel 11 Google V2 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-v2-contact-us

Recommended Laravel Tutorials

Leave a Comment