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:
-
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.
-
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.
-
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
-
Configuration:
After installation, open your
.env
file and add your reCAPTCHA keys:NOCAPTCHA_SECRET=your-secret-key NOCAPTCHA_SITEKEY=your-site-key
-
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>
-
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', ]);
-
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
-
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.