In Laravel, when you create a custom validation rule, you typically return true or false to indicate whether the validation passed or failed. However, if you want to return additional data such as the ReCAPTCHA score for logging purposes, you can't directly return it from the validation rule itself.
Instead, you can use the Laravel's Validator facade to hook into the validation process and store the additional data you need. Here's how you can do it:
- Create a custom validation rule for ReCAPTCHA.
- Store the score in the session or pass it through an event.
- Log the score after the validation is completed.
Here's an example of how you might implement this:
// Create a custom validation rule
use Illuminate\Contracts\Validation\Rule;
class Recaptcha implements Rule
{
public $score;
public function passes($attribute, $value)
{
// Perform ReCAPTCHA validation and store the score
$recaptchaResponse = $this->validateRecaptcha($value);
$this->score = $recaptchaResponse->score;
// You might want to store the score in the session or dispatch an event here
session(['recaptcha_score' => $this->score]);
// Return true or false based on the validation
return $recaptchaResponse->success;
}
public function message()
{
return 'The ReCAPTCHA verification failed.';
}
protected function validateRecaptcha($value)
{
// Your ReCAPTCHA validation logic here
// This should return an object or array with 'success' and 'score' properties
}
}
Then, when you use this rule in a form request, you can retrieve the score from the session or listen for the event you dispatched and log the score:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'g-recaptcha-response' => ['required', new Recaptcha],
]);
if ($validator->fails()) {
// Handle the failed validation
} else {
// The validation passed, you can log the score now
$score = session('recaptcha_score', null);
// Log the score
\Log::info("ReCAPTCHA score: {$score}");
// Continue with your controller logic
}
}
Remember to clear the session after logging the score to avoid old scores being logged on subsequent requests.
This approach allows you to perform the validation and also use the score for logging or any other purposes you might have.