Google trends Public Holidays Coupon Code Code Compiler

How to Add Google reCAPTCHA to Laravel Forms


Nov 8, 2023

How to Add Google reCAPTCHA to Laravel Forms

Boost your Laravel website's security with Google reCAPTCHA integration. Follow this comprehensive guide to add an extra layer of protection to your forms and safeguard against spam and bots.

In the ever-evolving landscape of web development, security remains a paramount concern. Laravel, one of the most popular PHP frameworks, provides an extensive set of tools and features for building robust and secure web applications. One essential aspect of security is protecting your web forms from spam and automated bots. Google reCAPTCHA is a widely used tool to achieve this, and in this article, we'll walk you through the process of adding Google reCAPTCHA to your Laravel forms.

Why Use Google reCAPTCHA?

Google reCAPTCHA is a free and effective way to defend your web forms from automated attacks. It's designed to distinguish between humans and bots, ensuring that only real users can submit your forms. By integrating Google reCAPTCHA, you can significantly reduce the volume of spam submissions, enhance the user experience, and bolster the security of your Laravel application.

Prerequisites

Before we dive into the implementation, make sure you have the following prerequisites in place:

  1. A working Laravel project.
  2. A Google account (to set up reCAPTCHA keys).

Step 1: Create a Google reCAPTCHA Site

  1. Go to the Google reCAPTCHA website (https://www.google.com/recaptcha/admin/create) and log in with your Google account.
  2. Choose the "reCAPTCHA v2" option.
  3. Select "I'm not a robot" Checkbox.
  4. In the Domains section, enter your website domain(s) where the reCAPTCHA will be used. For development purposes, you can use "localhost" as one of the domains.
  5. Accept the reCAPTCHA Terms of Service, and click the "Submit" button.

After completing these steps, you will receive two keys - a site key and a secret key. You'll need these keys to integrate reCAPTCHA into your Laravel forms.

Step 2: Integrate Google reCAPTCHA in Laravel

Now, let's integrate reCAPTCHA into your Laravel project:

  1. Open your Laravel project and locate the .env file in the root directory.

  2. Add your reCAPTCHA keys to the .env file like this:

    
    RECAPTCHA_SITE_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    RECAPTCHA_SECRET_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    RECAPTCHA_SITE=https://www.google.com/recaptcha/admin/
    
    
  3. Next, open the Laravel view where you want to add reCAPTCHA. Typically, this is a contact form or a registration form.

  4. In the form, add the reCAPTCHA widget. Place the following code within your form tag:

    
     <!-- Google Recaptcha Widget-->
    <div class="g-recaptcha mt-4" data-sitekey={{config('services.recaptcha.key')}}></div>
    
    
  5. Add google recaptcha script at top in head section at the same form page.

    
    <script async src="https://www.google.com/recaptcha/api.js"></script>
    
    
  6. Now, create a new configuration in the config/services.php file. This file is used when you want to add third-party configurations. So, here we will add recaptcha keys provided by Google.

    
    'recaptcha' => [
            'key' => env('RECAPTCHA_SITE_KEY'),
            'secret' => env('RECAPTCHA_SECRET_KEY'),
        ]
     
    
    
  7. Finally, you need to validate the reCAPTCHA response in your Laravel controller. In the controller method that handles the form submission, add the following code:

Step 4: Use Google reCAPTCHA Validation

You can use the "recaptcha" rule to validate reCAPTCHA responses in your form requests. For example, in a custom form request class, you can do the following:

This step streamlines the validation process, making it easy to incorporate reCAPTCHA into multiple forms across your Laravel application.


use Illuminate\Support\Facades\Http;
use Symfony\Component\HttpFoundation\IpUtils;

public function store(ContactRequest $request): RedirectResponse
{
 $recaptcha = $request->input('g-recaptcha-response');

 if (is_null($recaptcha)) {
    $request->session()->flash('message', "");
  return redirect()->back();
 }

 $url = "https://www.google.com/recaptcha/api/siteverify";

 $params = [
  'secret' => config('services.recaptcha.secret'),
  'response' => $recaptcha,
  'remoteip' => IpUtils::anonymize($request->ip())
 ];
  $resp>post($url, $params);

 $result = json_decode($response);

 if ($response->successful() && $result->success == true) {
  $request->session()->flash('message', "");
  return redirect()->back();
  
 } else {
  $request->session()->flash('message', "");
  return redirect()->back();
 }
}

Conclusion

In this article, we've explored the importance of securing your Laravel forms and how Google reCAPTCHA can help you achieve this goal. By following the steps outlined above, you can integrate reCAPTCHA into your Laravel project effectively, fortifying your application against spam and bot-driven attacks.

Enhancing the security of your web forms not only protects your users but also maintains the integrity of your data. Implementing Google reCAPTCHA is a valuable step towards building a safer and more reliable Laravel application.

Copyright 2024. All rights are reserved