In this episode, we're cleaning up our code by moving the reCAPTCHA verification into its own middleware. Instead of repeating the token validation in every controller or route, we create a dedicated VerifyRecaptchaToken
middleware that can just be attached to any route we want to protect. This makes the code much tidier and reusable!
We set up the middleware and register it in Laravel's kernel so we can use it by a simple name (recaptcha
) on our routes, like in the authentication flow. Then, we test it to make sure that when the user submits a login form, the token is being processed by our middleware.
After that, it's time to actually talk to Google's reCAPTCHA API. We use Laravel's HTTP client to send the necessary data (the token, secret key, and optionally the user's IP address) as a form POST, and grab the response as an object. We look at what's in the response—like the success
flag and the all-important score
. Depending on these, we handle failed or successful validations (for now, just with dd()
calls to see what happens).
At the end, we discuss next steps: we'll clean up these responses so they don't just dump to the screen, let the threshold score be easily configurable, and create a Blade directive to reuse reCAPTCHA in any form. So now, we've got reCAPTCHA validation working in middleware, making our authentication routes safer and our code much cleaner!