Integrating Google reCAPTCHA v3 into a Laravel application can enhance its security by protecting against automated attacks while providing a seamless user experience. Below is a comprehensive guide on how to implement Google reCAPTCHA v3 in Laravel along with an example tutorial.
Step 1: Register Your Site with Google reCAPTCHA v3
- Go to the Google reCAPTCHA website and sign in with your Google account.
- Register your site/domain to obtain the necessary site and secret keys.
Step 2: Install Google reCAPTCHA Package
In your Laravel project directory, use Composer to install the google/recaptcha
package:
composer require google/recaptcha
Step 3: Configure Laravel Environment
Add your reCAPTCHA site and secret keys to the .env
file:
RECAPTCHA_SITE_KEY=your_site_key
RECAPTCHA_SECRET_KEY=your_secret_key
Step 4: Implement reCAPTCHA in Laravel Forms
- Add reCAPTCHA to Your Form: Insert the reCAPTCHA widget within your Laravel Blade template’s form:
<form action="/submit-form" method="post">
@csrf
<!-- Your other form fields -->
<div class="g-recaptcha" data-sitekey="{{ env('RECAPTCHA_SITE_KEY') }}"></div>
<button type="submit">Submit</button>
</form>
- Verify reCAPTCHA Token: In your controller method handling form submission, validate the reCAPTCHA token received from the form:
use Illuminate\Http\Request;
use GuzzleHttp\Client;
public function submitForm(Request $request)
{
$token = $request->input('g-recaptcha-response');
$client = new Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET_KEY'),
'response' => $token,
]
]);
$body = json_decode((string)$response->getBody());
if ($body->success) {
// reCAPTCHA validation passed, continue with form submission
} else {
// reCAPTCHA validation failed, handle accordingly
}
}
Step 5: Test and Verify
Test your form submission process to ensure reCAPTCHA validation is working correctly. Google reCAPTCHA v3 assigns a score to each request based on its perceived level of bot-like behavior, eliminating the need for interactive challenges.
By following these steps, you can seamlessly integrate Google reCAPTCHA v3 into your Laravel application, enhancing its security posture while maintaining a smooth user experience.