Google recaptcha is a free service provided by Google, which protects your website from unwanted spams and abuse.
This article help you to create Custom Laravel Form Validation for Recaptcha.
Before us being, you need the following:
- Google reCAPTCHA
- Guzzle, an extensible PHP HTTP client:
To install Guzzle via composer: composer require guzzlehttp/guzzle
We will create a custom validator, a PHP class named GoogleReCaptcha. Create a new folder inside your app folder named CustomValidator.
File: App\CustomValidator\GoogleReCaptcha.php
namespace App\CustomValidator;
use GuzzleHttp\Client;
class GoogleReCaptcha
{
public function validateRecaptcha($attribute, $value, $parameters, $validator){
try{
$client = new Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify',
['form_params'=>
[
'secret'=> /*You ReCaptcha Secret Key*/,
'response'=>$value
]
]
);
$body = json_decode((string)$response->getBody());
return $body->success;
}
catch (\Exception $e) {
return false;
}
}
}
Add the custom validator to App Service Provider:
File: App\Providers\AppServiceProvider.php
public function boot()
{
Validator::extend(
'recaptcha',
'App\CustomValidators\GoogleReCaptcha@validateReCaptcha'
);
}
Now we can use recaptcha as form validation rule for and request.
Example: Validation rule for contact us form
File: App\Requests\ContactUs;
use Illuminate\Foundation\Http\FormRequest;
class CreateHireMeRequest extends Request
{
public function authorize()
{
return true;
}
public function messages()
{
return [
'recaptcha'=> 'Please ensure that you are not a robot…'
];
}
public function rules()
{
return [
'g-recaptcha-response'=>'required|recaptcha',
];
}
}
The message function will return the recaptcha message if recaptcha validation fails.