hannebaumsaway
hannebaumsaway

Reputation: 2734

Implementing reCaptcha in Laravel 8.2

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.)

Upvotes: 0

Views: 229

Answers (1)

linktoahref
linktoahref

Reputation: 7972

Since you are using a closure instead of a dedicated controller, you could add the validation rule to the request object as:

Route::post('/contact', function(Request $request) {
    $request->validate([
        'g-recaptcha-response' => 'recaptcha'
    ]);

    Mail::to('<my email address>')->send(new ContactMail($request));

    return redirect()->route('thank-you');
});

PS: It is better to use a Controller than a Closure for complex calculations

Upvotes: 1

Related Questions