Laravel Google ReCaptcha V2 Example; In this tutorial we will show you how to add google reCaptcha v2 in laravel form with validation. Google ReCaptcha is a captcha like a system, that provides security against hackers and sticks or CURL requests.
Google recaptcha is very popular now a days, so here we will add “I’m not a robot” captcha in the contact form of our Laravel application. Google captcha is best to remove the spam from contanct form and also available many laravel package but we implement google recaptcha in laravel contact form without package.
How to use google recaptcha v2 in laravel with validation
Follow the following steps to integrate google reCaptha v2 in laravel for contact form with validation.
- Step 1: Download Laravel App
- Step 2: Connect App To Database
- Step 3: Get Google reCAPTCHA API Key
- Step 4: Add Routes
- Step 5: create Controller
- Step 6: Add Rule Validation for Recaptcha
- Step 7: Create Blade File
- Step 8: Start Development Server
Download Laravel App
First at all, create new laravel 9 application using the following command in terminal.
composer create-project --prefer-dist laravel/laravel laravel-google-recaptcha
Now Go inside the app:
cd laravel-google-recaptcha
Connect App To Database
Open the .env file and add your database credentials such as database name, username equally important password:
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
Get Google reCAPTCHA API Key
We have to create a Google reCAPTCHA project. Visit reCAPTCHA admin panel and create a project. Select version 2.
Then hit submit button to get the site and secret key and update in .env file like site and secret key in this two variables just like below.
.env
RECAPTCHA_SITE_KEY=site_key
RECAPTCHA_SECRET_KEY=secret_key
Add Routes
We have created two methods in the ContactFormController. Let’s define two routes for the two methods. Open routes/web.php and paste this code:
routes\web.php
Route::get('contact-us', 'ContactController@getContacts');
Route::post('contact-us', 'ContactController@saveContacts')->name('contact-us');
Create Controller
Let’s create a controller named “ContactController” by typing this command:
php artisan make:controller ContactController
app\Http\Controllers\ContactController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Contact;
use App\Rules\GoogleRecaptcha;
class ContactController extends Controller
{
public function getContacts() {
return view('contact-us');
}
public function saveContacts(Request $request) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'subject' => 'required',
'phone_number' => 'required',
'message' => 'required',
'g-recaptcha-response' => ['required', new GoogleRecaptcha]
],[ 'g-recaptcha-response.required' => 'The recaptcha field is required.']);
Contact::create([
'name' => $request->name,
'email' => $request->email,
'subject' => $request->subject,
'phone_number' => $request->phone_number,
'message' => $request->message,
]);
return back()->with('success', 'Thank you for contact us!');
}
}
Add Rule Validation for Recaptcha
Now use the following command to create a validation rule for google recaptcha.
php artisan make:rule GoogleRecaptcha
app\Rules\GoogleRecaptcha.php
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use GuzzleHttp\Client;
class GoogleRecaptcha implements Rule
{
public function passes($attribute, $value)
{
$client = new Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify',
[
'form_params' => [
'secret' => env('RECAPTCHA_SECRET_KEY', false),
'remoteip' => request()->getClientIp(),
'response' => $value
]
]
);
$body = json_decode((string)$response->getBody());
return $body->success;
}
public function message()
{
return 'Are you a robot?';
}
}
Create a Blade File
Now create a blade file which will show the contact form. So, navigate the resources/views directory and create “contact-us” page. Next, open the resources/views/contact-us.blade.php file and put the following code on it;
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="card-user">
<div class="card-header">
<h5 class="card-title">Contact Us</h5>
</div>
<div class="card-body">
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
@endif
<form method="post" action="{{ route('contact-us') }}">
{{csrf_field()}}
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label> Name </label>
<input type="text" class="form-control @error('name') is-invalid @enderror" placeholder="Name" name="name">
@error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label> Email </label>
<input type="text" class="form-control @error('email') is-invalid @enderror" placeholder="Email" name="email">
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label> Phone Number </label>
<input type="text" class="form-control @error('phone_number') is-invalid @enderror" placeholder="Phone Number" name="phone_number">
@error('phone_number')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label> Subject </label>
<input type="text" class="form-control @error('subject') is-invalid @enderror" placeholder="Subject" name="subject">
@error('subject')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label> Message </label>
<textarea class="form-control textarea @error('message') is-invalid @enderror" placeholder="Message" name="message"></textarea>
@error('message')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
</div>
<div class="form-group">
<div class=" g-recaptcha" data-sitekey="{{ env('RECAPTCHA_SITE_KEY') }}"></div>
@if ($errors->has('g-recaptcha-response'))
<span class="text-danger">{{ $errors->first('g-recaptcha-response') }}</span>
@endif
</div>
<div class="form-group">
<div class="update ml-auto mr-auto">
<button type="submit" class="btn btn-primary btn-round">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://www.google.com/recaptcha/api.js"></script>
</body>
</html>
Run Development Server and Test
Run the php artisan serve command in your terminal and hit the below url in browser.
http://localhost:8000/contact-us
You will see the output like this:
I hope you enjoy with this tutorial.