reCaptcha 2 in Laravel einbauen

The current challenge at our web agency is: How do I secure my contact form with Google reCAPTCHA v2? First, we install the required Biscolab extension via Composer using require biscolab/laravel-recaptcha. We then follow the manual at https://laravel-recaptcha-docs.biscolab.com/docs/intro and create the configuration file using php artisan vendor:publish --provider="Biscolab\ReCaptcha\ReCaptchaServiceProvider". Finally, we add the keys we previously obtained from Google (Site Key and Secret Key) to the .env file.

 

Now we call the required function in our header file:

 

 

\resources\views\layouts\partials\header.blade.php using the following snippet.

 

{!! htmlScriptTagJsApi($configuration) !!}

 

and then integrate the reCAPTCHA into the relevant form, in our case:

 

 /resources/views/pages/contact.blade.php

 

Here, the snippet needs to be inserted:

 

{!! htmlFormSnippet() !!}

 

needs to be added, and optionally an error message with:

 

<div class="form-group{{ $errors->has('g-recaptcha-response') ? ' has-error' : '' }}">

                <div class="col-lg-offset-3 col-lg-9 col-md-offset-4 col-md-8 col-sm-offset-5 col-sm-7">

                               {!! htmlFormSnippet() !!}

                               @if ($errors->has('g-recaptcha-response'))

                                               <span class="help-block">

                                                               <strong>{{ $errors->first('g-recaptcha-response') }}</strong>

                                               </span>

                               @endif                                                                                                                              

                </div>

</div> 

 

Then we also need to add reCAPTCHA to the validation. We do this in the file:

 

/app/Http/Controllers/ContactController.php

 

in the function

 

public function sendForm(Request $request)

 

with the additional line

 

recaptchaFieldName() => recaptchaRuleName(),

 

Then we add the desired error messages in the available languages, for example in:

 

/resources/lang/de/validation.php

 

and 

 

/resources/lang/en/validation.php

 

The identifier here is "recaptcha", so the line in German could, for example, read:

 

'recaptcha' => 'Please check "I'm not a Robot" checkbox!'

 

That's it! We tested it at our web agency on a website running Laravel 6.0.4.