Google Recaptcha V3 Example Tutorial in Laravel 8 Jetstream with Inertia

I am goin to show you how to add google recaptcha v3 in your laravel jetstream with inertia web application. In this example I assume that already have installed your application with the auth scafold

 · 2 min read

Hello there,

I am goin to show you how to add google recaptcha v3 in your laravel jetstream with inertia web application. In this example I assume that already have installed your application with the auth scafolding. We will add to the registration page, but you can use the same to put it everywhere.

Step 1

In file resources/views/app.blade.php add in header section below:

<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>

With above line the recaptca icon should appear.

Step 2

In file resources/js/Pages/Auth/Register.vue

In the form definition add variable captcha_token as indicated below.

data() {
    return {
      form: this.$inertia.form({
        name: "",
        email: "",
        password: "",
        password_confirmation: "",
        terms: false,
        captcha_token: "",
      }),
    };
  },

Replace function submit with below code:

submit() {
      let submitForm = (token) => {
        this.form.captcha_token = token;
        this.form.post(this.route("register"), {
          onFinish: () => this.form.reset("password", "password_confirmation"),
        });
      };

      grecaptcha
        .execute(process.env.MIX_CAPTCHA_KEY, { action: "submit" })
        .then(function (token) {
          submitForm(token);
        });
    },

Step 3

Add a new rule with command:

php artisan make:rule Recaptcha

Edit file app/Actions/Fortify/CreateNewUser.php and add the rule in validation as indicated below:

$input = Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => $this->passwordRules(),
            'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
            'captcha_token' => ['required', new Recaptcha]
        ])->validate();

Edit file app/Rules/Recaptcha.php and add below code:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Http;

class Recaptcha implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $response = Http::asForm()->post("https://www.google.com/recaptcha/api/siteverify", [
            'secret' => config('services.recaptcha.secretkey'),
            'response' => $value
        ]);

        if ($response->successful() && $response->json('success') && $response->json('score') > 0.5) {
            return true;
        }

        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Failed captcha validation.';
    }
}

Step 4

Add in your environment file the follow variables. Replace xxx and yyy with your keys.

MIX_CAPTCHA_SITE_KEY=xxx
CAPTCHA_SECRET_KEY=yyy

In file config/services.php add the follow entry:

'recaptcha' => [
        'secretkey' => env('CAPTCHA_SECRET_KEY'),
    ],

If you do not have above file, you can also add above key in config/app.php, but make the necessary changes where is called.

That's it!!!