Hello Coders !!
This article is about the Google reCaptcha Integration in Laravel 5.x with an example. Google reCaptcha Integration in Laravel is the topic, we are going to discuss today. The Google reCaptcha is an associate open service that defends your website from spam and abuse.
It uses advanced risk analysis techniques to indicate humans and bots apart. exploitation reCaptcha, you need to sign up for the API key combine for your website. The key pair consists of the positioning key and the secret key. during this example, we can follow step by step method to implement it.
First, you will need a Google Account where you will create ReCaptcha for your domain.
We can use localhost for the testing in the domain section
Follow the below steps to complete guide
Step 1. Install laravel application.
Please refer article for this > [How to install Laravel 5.X] for how to install Laravel
Step 2. Get Key and Secret from google account.
Get key and secret from google account and add it into the .env file as mentioned below
G_RECAPTCHA_KEY=ADD_GOOGLE_RECAPTCHA_KEY_HERE
G_RECAPTCHA_SECRET=ADD_GOOGLE_RECAPTCHA_SECRET_HERE
Step 3. Create a controller and view file as mentioned below.
$ php artisan make:controller PollController
<?php
#Path: app/Http/Controllers/PollController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\PollRequest;
class PollController extends Controller
{
function index(){
return view('welcome');
}
// Once form will be submitted successfully it will comes to this action.
function submit(PollRequest $request){
$input = $request->all();
// We can write further logic here if want to store data into the database
return back()->with('success_msg', 'Data submitted successfully. Thank you!');
}
}
Then create a view file as below in path: resources/views/welcome.blade.php
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<!-- Fonts -->
<link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- Styles -->
</head>
<body class="gradient">
@if(session('success_msg'))
<div class="alert alert-success fade in alert-dismissible show text-center">
{{ session('success_msg') }}
</div>
@endif
<form action="{{ route('pollsubmit') }}" method="post" id="recaptcha_frm" name="recaptcha_frm">
@csrf
<section class="container mt-2 mb-2">
<div class="container-fluid">
<div class="title m-b-md">
<a href="https://github.com/developer-ashok/laravel-recaptcha" style="color: #fff">
<h3>
<center>Laravel + Google reCaptcha Example </center>
</h3>
</a>
</div>
<div class="row flex-xl-nowrap">
<div class="card mr-3">
<a href="https://www.officialtrailers.in/post/avengers-endgame" target="_blank">
<img class="card-img-top" src="{{ asset('css/1.jpg') }}" alt="Card image cap">
</a>
<div class="card-body">
<h5 class="card-title">Avengers Endgame</h5>
<p class="card-text">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p>
<label class="btn btn-danger">
<input type="radio" name="radio" id="radio" value="1" {{ (old( 'radio')==1 ) ? 'checked' : '' }} class="form-control" /> I Like This
</label>
</div>
</div>
<div class="card mr-3">
<a href="https://www.officialtrailers.in/post/men-in-black-international" target="_blank">
<img class="card-img-top" src="{{ asset('css/2.jpg') }}" alt="Card image cap">
</a>
<div class="card-body">
<h5 class="card-title">Men in Black: International</h5>
<p class="card-text">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p>
<label class="btn btn-danger">
<input type="radio" name="radio" id="radio" value="2" {{ (old( 'radio')==2 ) ? 'checked' : '' }} class="form-control" /> I Like This
</label>
</div>
</div>
<div class="card mr-3">
<a href="https://www.officialtrailers.in/post/captain-marvel-official-trailer" target="_blank">
<img class="card-img-top" src="{{ asset('css/3.jpg') }}" alt="Card image cap">
</a>
<div class="card-body">
<h5 class="card-title">Captain Marvel</h5>
<p class="card-text">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p>
<label class="btn btn-danger">
<input type="radio" name="radio" id="radio" value="3" {{ (old( 'radio')==3 ) ? 'checked' : '' }} class="form-control" /> I Like This
</label>
</div>
</div>
</div>
@if ($errors->has('radio'))
<div class="alert alert-danger mt-3" role="alert" style="width: 40%">
<strong>{{ $errors->first('radio') }}</strong>
</div>
@endif
<div class="row mt-4">
<div class="col-sm-4">
<div class="g-recaptcha" data-sitekey="{{ env('G_RECAPTCHA_KEY') }}"></div>
</div>
<div class="col-sm-3">
<input type="submit" class="btn btn-success" style="height: 95%; width: 100%; font-size: 45px; font-weight: bold;" />
</div>
</div>
@if ($errors->has('g-recaptcha-response'))
<div class="alert alert-danger mt-3" style="width: 40%" role="alert">
<strong>{{ $errors->first('g-recaptcha-response') }}</strong>
</div>
@endif
</section>
</form>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</body>
</html>
Step 4. Create route in web.php file
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('poll','PollController@index')->name('poll');
Route::post('pollsubmit','PollController@submit')->name('pollsubmit');
Here I have added an example of voting poll functionality to understand the use case
Step 5. Create request file for validation
$ php artisan make:request PollRequest
Add Below code in request file path: app/Http/Requests/PollRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Validators\ReCaptcha;
class PollRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true; // Make sure this should be true if we need to access this without login
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'radio'=>'required',
'g-recaptcha-response'=>'required|recaptcha'
];
}
public function messages()
{
return [
'g-recaptcha-response.required'=>'Please ensure that you are a human!',
'g-recaptcha-response.recaptcha'=>'Please ensure that you are a human!'
];
}
}
Step 6. Create validators for recaptcha
<?php
#Path: app/Validators/ReCaptcha.php
namespace App\Validators;
use GuzzleHttp\Client;
class ReCaptcha
{
public function validate($attribute, $value, $parameters, $validator){
$client = new Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify',
['form_params'=>
[
'secret'=>env('G_RECAPTCHA_SECRET'),
'response'=>$value
]
]
);
$body = json_decode((string)$response->getBody());
return $body->success;
}
}
Step 7. Final step, update app service provider.
<?php
#Path: app/Providers/AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Validator::extend(
'recaptcha',
'App\\Validators\\ReCaptcha@validate'
);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
Now run laravel using below command and get the output.
$ php artisan serve
This article is about the Google reCaptcha Integration in Laravel 5.x with an example and we are done with Google reCaptcha integration in Laravel. Here I am attaching a git repository for better understanding.
Greate post. Keep posting such kind of info on your
blog. Im really impressed by your blog.
Hi there, You have performed a fantastic job. I will definitely
digg it and in my view suggest to my friends.
Thank You !!
Really appreciate you sharing this blog.Really looking forward to read more. Awesome.
Admiring the hard work you put into your site
and in depth information you provide. It’s good to come across a blog every once
in a while that isn’t the same old rehashed information. Great
read! I’ve saved your site and I’m including your RSS feeds to
my Google account.
Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your weblog posts.
In any case I’ll be subscribing to your feed and I hope you
write once more very soon!