Google Recaptch

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:

  1. Google reCAPTCHA
  2. 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.


Tags: Php   Laravel  

Related

PHP

Custom form request for Google Recaptcha.

PHP

Increase site speed using Redis as a caching server.

PHP

This article will cover how to deploy a Laravel project in shared hosting.

PHP

Tagging is a popular way of categorizing posts in any blog or news related sites.

keyboard_arrow_up