Hi Brothers ,
This is a short guide on how to use google recaptcha in laravel. This post will give you a simple example of add google recaptcha in laravel. I would like to share with you laravel google recaptcha validation. you'll learn google recaptcha code in laravel.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.
As we know, When we created a contact us form or feedback form or any form that is accessed publicly Then we have so many submissions from spam. They submit those forms using curl request or something. So we can not get the real users from those forms. Here, i we will use google recaptcha v3 to prevent spam submission. we will create a contact us form and use google recaptcha v3 and prevent them. So that way you have only real users and real feedback you will get.
Let's see the below steps and make it done.
composer create-project laravel/laravel example-app
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
https://www.google.com/recaptcha/admin/create
after sucessfully register you can get site key and secret key from like bellow preview.
open .env file and add this two variable
.env
GOOGLE_RECAPTCHA_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
GOOGLE_RECAPTCHA_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxx
In this step, we will create two routes GET and POST. so let's add it.
routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;
/*
|--------------------------------------------------------------------------
| 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('contact-us', [ContactController::class, 'index']);
Route::post('contact-us', [ContactController::class, 'store'])->name('contact.us.store');
In this step, we will create new "ReCaptcha" validation rule that will check user is real or not using google recaptcha v3 API. so let's run below command and update rule validation file.
php artisan make:rule ReCaptcha
app/Rules/ReCaptcha.php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Http;
class ReCaptcha implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct(){
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$response = Http::get("https://www.google.com/recaptcha/api/siteverify",[
'secret' => env('GOOGLE_RECAPTCHA_SECRET'),
'response' => $value
]);
return $response->json()["success"];
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The google recaptcha is required.';
}
}
In this step, we have to create new controller as ContactController and we have also need to add two methods index() and store() on that controller. We will use recaptcha validation on store method. so let's update follow code:
app/Http/Controllers/ContactController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Rules\ReCaptcha;
class ContactController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(){
return view('contactForm');
}
/**
* Write code on Method
*
* @return response()
*/
public function store(Request $request)
{
$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();
dd($input);
return redirect()->back()->with(['success' => 'Contact Form Submit Successfully']);
}
}
create contactForm.blade.php(resources/views/contactForm.blade.php) for create form with google recaptcha v3 and put following code
resources/views/contactForm.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Google ReCaptcha V3 Example - toolarena.in</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 Google ReCaptcha V3 Example - toolarena.in</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('token'))
<span class="text-danger">{{ $errors->first('token') }}</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="token" value="' + token + '">');
$('#contactUSForm').unbind('submit').submit();
});;
});
});
</script>
</html>
Run Laravel App:
php artisan serve