Add Google reCAPTCHA in Laravel Breeze Registration

Add Google reCAPTCHA in Laravel Breeze Registration

Step 1: Obtaining reCAPTCHA Keys

Go to the Google reCAPTCHA website (https://www.google.com/recaptcha) and sign in with your Google account. Click the + sign and fill in the details as follows:

Label: use the domain name of your application

reCAPTCHA type: Select challenge(v2) and tick I’m not a robot checkbox

Domain: in our case add 127.0.0.1 since you are on a local machine but you can change this later to your domain name once on the live server or just add the domain name you will use.

Click submit to generate your site keys

Once the keys are generated copy them and paste them somewhere else as they will be needed later.

Step 2: Installing NoCaptcha Laravel Package

Run this command to install NoCaptcha Package.

composer require anhskohbo/no-captcha

After the package is installed, open your config/app.php file and add the following line to the providers array.

Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class,

Next, run the following command to publish the package configuration file.

php artisan vendor:publish --provider="Anhskohbo\NoCaptcha\NoCaptchaServiceProvider"

Step 3: Configuring NoCaptcha Package

Open the generated config/nocaptcha.php file. In this file, we will need to supply the NOCAPTCHA_SECRET and NOCAPTCHA_SITEKEY on the .env file.

Go to .env file and paste your site keys as shown below

Step 4: Updating Laravel Breeze Registration Views

Open the resources/views/auth/register.blade.php file. and add the following before the submit button.

<!-- google recaptch -->
  <div class="mt-4">
      {!! NoCaptcha::renderJs() !!}
      {!! NoCaptcha::display() !!}
      @if ($errors->has('g-recaptcha-response'))
      <x-input-error :messages="$errors->first('g-recaptcha-response')" />
      @endif
  </div>

Step 5: Updating Laravel Breeze Registration Controller

Open the app/Http/Controllers/Auth/RegisteredUserController.php file. and add the following code to the store method to validate the reCAPTCHA response.

$this->validate($request, [
    // Existing validation rules...
    'g-recaptcha-response' => 'required|captcha',
],['g-recaptcha-response' => 'Please Verify you are not a robot']);

Note: [‘g-recaptcha-response’ => ‘Please Verify you are not a robot’] used to set a more user friendly message in case of an error.

Start the server and go to http://localhost:8000/register)

You should see the new checkbox of Google Recaptcha