Laravel 9 Google ReCAPTCHA Tutorial Example
Firstly, you need to obtain API keys from the Google ReCAPTCHA website: https://www.google.com/recaptcha. You'll get a site key and a secret key.
Next, you can follow these steps:
Step 1: Install Laravel
Assuming you have Composer installed, you can create a new Laravel project using the following command:
composer create-project laravel/laravel your-project-name
cd your-project-name
Step 2: Install the reCAPTCHA package
You can use the "anhskohbo/no-captcha" package for Laravel. Install it via Composer:
composer require anhskohbo/no-captcha
Step 3: Configure your .env file
Add your Google ReCAPTCHA keys to your .env file:
NOCAPTCHA_SECRET=your-secret-key
NOCAPTCHA_SITEKEY=your-site-key
Step 4: Configure Laravel
In your config/app.php
file, add the following to the providers
array:
'providers' => [
// ...
Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class,
],
Also, add the following to the aliases
array in the same file:
'aliases' => [
// ...
'NoCaptcha' => Anhskohbo\NoCaptcha\Facades\NoCaptcha::class,
],
Step 5: Create a contact form
Create a simple contact form in your resources/views/contact.blade.php
:
<form method="POST" action="{{ route('contact') }}">
@csrf
{!! NoCaptcha::renderJs() !!}
{!! NoCaptcha::display() !!}
<button type="submit">Submit</button>
</form>
Step 6: Handle the form submission
In your app/Http/Controllers/ContactController.php
:
use Illuminate\Http\Request;
use Validator;
class ContactController extends Controller
{
public function showForm()
{
return view('contact');
}
public function submitForm(Request $request)
{
$validator = Validator::make($request->all(), [
'g-recaptcha-response' => 'required|captcha',
// Add other form validation rules here
]);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
// Process the form submission
// ...
return redirect()->route('contact')->with('success', 'Form submitted successfully!');
}
}
Step 7: Define routes
In your routes/web.php
:
use App\Http\Controllers\ContactController;
Route::get('/contact', [ContactController::class, 'showForm'])->name('contact');
Route::post('/contact', [ContactController::class, 'submitForm']);
Step 8: Display success message
In your resources/views/contact.blade.php
, display the success message:
@if(session('success'))
<p>{{ session('success') }}</p>
@endif
Step 9: Test
Run your Laravel development server:
php artisan serve
Visit http://localhost:8000/contact
in your browser and test the form.
Remember to check the Laravel documentation and the documentation of the packages you are using for any updates or changes.