How to validate recaptcha with laravel and vue.js?

by raven_corwin , in category: PHP Frameworks , 2 months ago

How to validate recaptcha with laravel and vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 2 months ago

@raven_corwin 

To validate reCaptcha with Laravel and Vue.js, you can follow these steps:

  1. Add Google reCaptcha to your Vue.js component:
1
2
3
<div>
    <div id="recaptcha"></div>
</div>


  1. Include reCaptcha script in the head section of your HTML file:
1
2
3
<head>
    <script src="https://www.google.com/recaptcha/api.js"></script>
</head>


  1. Add JavaScript code to handle reCaptcha validation in your Vue.js component:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var app = new Vue({
    el: '#app',
    data: {
        recaptchaKey: 'your-recaptcha-key',
        recaptchaResponse: ''
    },
    methods: {
        onRecaptchaVerified: function(response) {
            this.recaptchaResponse = response;
        },
        verifyRecaptcha: function() {
            axios.post('/verifyRecaptcha', {
                recaptchaResponse: this.recaptchaResponse
            })
            .then(function(response) {
                // Handle response
            })
            .catch(function(error) {
                // Handle error
            });
        }
    },
    mounted: function() {
        var self = this;
        grecaptcha.render('recaptcha', {
            sitekey: this.recaptchaKey,
            callback: function(response) {
                self.onRecaptchaVerified(response);
            }
        });
    }
});


  1. Create a route in your Laravel application to handle the reCaptcha verification:
1
Route::post('/verifyRecaptcha', 'RecaptchaController@verifyRecaptcha');


  1. Create a controller method to verify the reCaptcha token:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use IlluminateHttpRequest;

class RecaptchaController extends Controller
{
    public function verifyRecaptcha(Request $request)
    {
        $response = $request->input('recaptchaResponse');
        $secret = 'your-recaptcha-secret-key';

        $verify = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");

        $captcha_success = json_decode($verify);

        if ($captcha_success->success == false) {
            return response()->json(['error' => 'reCaptcha verification failed'], 400);
        }

        return response()->json(['success' => 'reCaptcha verification passed'], 200);
    }
}


  1. Make sure to include your reCaptcha keys (site key and secret key) in your environment configuration file (.env) for security reasons.


By following these steps, you can validate reCaptcha with Laravel and Vue.js in your application.