Skip to content

Instantly share code, notes, and snippets.

@jpalala
Created November 1, 2023 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpalala/782a1da6f58954a9971ddeac08e87c59 to your computer and use it in GitHub Desktop.
Save jpalala/782a1da6f58954a9971ddeac08e87c59 to your computer and use it in GitHub Desktop.
laravel how to captcha

You can add a CAPTCHA to your Laravel application to protect against spam in your contact form by using Google's reCAPTCHA service. Here's a step-by-step guide on how to do this:

  1. Register Your Site with Google reCAPTCHA:

    Visit the Google reCAPTCHA website and sign in with your Google account. Then, register your website or app to get the necessary API keys.

    • Choose "reCAPTCHA v2" and "I'm not a robot" Checkbox.
    • Enter the domains where you want to use reCAPTCHA.
  2. Get Your API Keys:

    After registering your site, you'll receive two keys: a "Site Key" (for the frontend) and a "Secret Key" (for the backend). Save these keys for later use.

  3. Install the Laravel reCAPTCHA Package:

    You can use a Laravel package like "anhskohbo/no-captcha" to integrate reCAPTCHA into your Laravel application. To install it, run:

    composer require anhskohbo/no-captcha
  4. Configuration:

    After installation, open your .env file and add your reCAPTCHA keys:

    NOCAPTCHA_SECRET=your-secret-key
    NOCAPTCHA_SITEKEY=your-site-key
    
  5. Integrate reCAPTCHA with Your Contact Form:

    Add the reCAPTCHA field to your contact form view, typically in your Blade template:

    <div class="g-recaptcha" data-sitekey="{{ config('services.nocaptcha.site') }}"></div>
  6. Validate the CAPTCHA:

    In your contact form's controller, you'll need to validate the reCAPTCHA response. Add the 'g-recaptcha-response' field to your validation rules.

    $validatedData = $request->validate([
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required',
        'g-recaptcha-response' => 'required|captcha',
    ]);
  7. Display Errors:

    In your Blade view, you can display any validation errors associated with the CAPTCHA field:

    @if ($errors->has('g-recaptcha-response'))
        <span class="help-block">
            <strong>{{ $errors->first('g-recaptcha-response') }}</strong>
        </span>
    @endif
  8. Submit Form:

    If the CAPTCHA is validated successfully, you can proceed to send the contact form.

That's it! You've added reCAPTCHA protection to your Laravel contact form. This will help protect your form from spam submissions. Make sure to follow best practices for form validation and spam protection to ensure a secure and user-friendly experience.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment