Open In App
Related Articles

Laravel Google reCaptcha without package

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Captcha validation is extremely vital for safeguarding kind submission from the sender. It helps us to protect specious kind submissions to our website by bots. There are several captcha solutions for reducing spam kind submission. Out of these, the Google reCaptcha is safer, reliable, and most important is it’s free. If you are looking for how to add Google reCaptcha in your website then this article is useful for you. In this article, we learn about, using laravel framework how to add Google reCaptcha without adding external package installation.

Steps to laravel Google reCaptcha validation: Below is the few steps following which we can use Google reCaptcha without package:

  1. Create a custom validation rule 
  2. Create Recaptcha class 
  3. Generate site key and secret key 
  4. Update.env file in your project 
  5. Create view file 
  6. Google reCaptcha validation

1. Create a custom validation rule: By default, the laravel has many more rules of validation, but there is no rule for Google reCaptcha validation. But using one command we can make a simple custom validation rule for Google reCaptcha. By using the below command we make our custom validation rule

php artisan make:rule Recaptcha

2. Create Recaptcha class: After successful execution of this command, the reCaptcha class will be created in the path app/Rules directory. Then write the below code in the reCaptcha class file. The important thing is this code can be reused in your next project.

PHP

<? php 
  namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Recaptcha implements Rule {
    public function __construct() {
  
    }
  
    public function passes($attribute, $value) {
        $data = array('secret' => env('GOOGLE_RECAPTCHA_SECRET'),
            'response' => $value);
  
        try {
            $verify = curl_init();
            curl_setopt($verify, CURLOPT_URL, 
            curl_setopt($verify, CURLOPT_POST, true);
            curl_setopt($verify, CURLOPT_POSTFIELDS, 
                        http_build_query($data));
            curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($verify);
  
            return json_decode($response) -> success;
        }
        catch (\Exception $e) {
            return false;
        }
    }
  
    public function message() {
        return 'ReCaptcha verification failed.';
    }
}
?>

                    

3. Generate site key and secret key: Click on Google recapture you will get one page-like form, as shown in the picture below:

Google reCaptcha form

By adding your site and details you will get your website key and secret key. Save that key in your device notepad for further process.

4. Update .env file: Update the .env file of your project with a secret key and site key (Note: add your own site key and secret key, that is saved in your notepad).

GOOGLE_RECAPTCHA_KEY=<site key> 
GOOGLE_RECAPTCHA_SECRET=<secret key>

5. Create a view file: Create a view or blade file to write the code where you want Google reCaptcha validation protection. You can use this code in any form that you want safely submit.

HTML

<!doctype html>
  
<html lang="en">
  
<head>
    <meta charset="utf-8">
    <meta name="viewport" 
          content="width=device-width, 
          initial-scale=1, shrink-to-fit=no">
  
    <!-- CSS -->
    <link rel="stylesheet" href=
            async defer></script>
</head>
  
<body>
    <div class="container mt-5">
        <div class="card">
            <div class="card-header text-center"
                  Google reCaptcha </div>
  
            <div class="card-body">
                <form action="validate-captcha.php" 
                      method="post">
  
                    <div class="form-group">
  
                        <label for="exampleInputEmail1">
                              First Name</label
                          <input type="text" name="name"
                            class="form-control" id="name" 
                               required="">
                    </div>
  
                    <div class="form-group">
  
                        <label for="exampleInputEmail1">
                              Email </label
                          <input type="email" name="email"
                            class="form-control" id="email" 
                               aria-describedby="emailHelp" 
                               required="">
                    </div>
  
                    <div class="form-group"
                          <label for="exampleInputEmail1">
                              Password</label
                          <input type="password" name="password" 
                               class="form-control" id="password" 
                               required="">
                      </div>
  
                    <div class="form-group"
                          <label for="exampleInputEmail1">
                              Confirm Password</label
                          <input type="password" name="cpassword" 
                               class="form-control" id="cpassword" 
                               required=""
                      </div>
  
                    <label>
                        <input type="checkbox" name="remember" 
                               style="margin-bottom:15px"
                             I Accepts terms and conditions
                    </label>
  
                    <script src="https://www.google.com/recaptcha/api.js" 
                            async defer></script>
                    <div class="g-recaptcha" id="feedback-recaptcha" 
                         data-sitekey="{{ env('GOOGLE_RECAPTCHA_KEY') }}">
                    </div>
                    <input type="submit" name="password-reset-token" 
                           class="btn btn-primary">
                </form>
            </div>
        </div>
    </div>
</body>
  
</html>

                    

6. Google reCaptcha validation: In the final step, we add a custom validation rule at path app\Rules\GoogleRecaptcha. Add the below code to your file.

PHP

public function postContactForm(Request $request) {
    $this -> validate($request, [
        'g-recaptcha-response' =>
        ['required', new Recaptcha()]]);
  
    // Recaptcha passed, do what ever you need
}

                    

Output:

Output



Last Updated : 17 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads