John Davidson

php - Implementing reCaptcha in Laravel 8.2

0 comments
Message:


I went through all the steps of this answer by @kjdion84, but I don't know what is meant by the last part:



Finally, add the new validation rule to your controller:


'g-recaptcha-response' => 'recaptcha'



This is my first Laravel project, and I don't know what to use as "my controller." I want to implement reCaptcha on my contact form, the action of which sends an email. The form itself is on contact.blade.php, and the submission is handled via a POST route like so (in web.php):


Route::post('/contact', function(Request $request) {
Mail::to('<my email address>')->send(new ContactMail($request));
return redirect()->route('thank-you');
});

ContactMail is in app/Http/Mail and is as follows:


<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Http\Request;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class ContactMail extends Mailable
{
use Queueable, SerializesModels;

public $email;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct(Request $request)
{
$this->email = $request;
}

/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject('Contact form submission')
->from($this->email->email, $this->email->name)
->to('<my email address>')
->view('email.contactmail');
}
}

Everything works with the form functionality; I just can't figure out how to actually get the reCaptcha validation in place. (See the linked answer from the beginning of my question for information on where I put other reCaptcha stuff.)



My Answer:
This last part is referring to adding the reCaptcha validation rule to your controller in Laravel.

In your controller where you are handling the form submission, you can add the reCaptcha validation rule like this:

php
$request->validate([
'g-recaptcha-response' => 'required|captcha'
]);


This code snippet is telling Laravel to validate the 'g-recaptcha-response' field in the form submission. The 'required' rule ensures that the field is not empty, and the 'captcha' rule checks if the reCaptcha response is valid.

Make sure to include the necessary use statement at the top of your controller file:

php
use App\Rules\Captcha;


This will allow Laravel to recognize the 'captcha' validation rule.

Rate this post

5 of 5 based on 6017 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us