To write custom validation for Google Captcha in Laravel without using a package, you’ll need to do the following:
1. Verify the Captcha response: You’ll need to send the Captcha response to the Google Captcha API and verify that it is valid. You can do this by sending a POST request to the following URL:
https://www.google.com/recaptcha/api/siteverify
You’ll need to include the following parameters in the request:
secret
: Your Captcha secret key.response
: The Captcha response that was submitted by the user.remoteip
: The IP address of the user.
The API will return a JSON response indicating whether the Captcha was successfully verified.
2. Create a custom validation rule: In your Laravel application, you can create a custom validation rule by creating a class that implements the Illuminate\Contracts\Validation\Rule
interface. Here’s an example of a custom validation rule that verifies a Captcha response:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use GuzzleHttp\Client;
class Captcha implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$client = new Client;
$response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('CAPTCHA_SECRET'),
'response' => $value,
'remoteip' => request()->ip(),
],
]);
$response = json_decode((string) $response->getBody());
return $response->success;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The Captcha verification failed. Please try again.';
}
}
3. Use the custom validation rule: Once you’ve created your custom validation rule, you can use your custom validation rule in a form request or a controller by adding the rule to the rules
array and using the validate
method.
For example, if you want to use the custom validation rule in a form request, you can do the following:
<?php
namespace App\Http\Requests;
use App\Rules\Captcha;
use Illuminate\Foundation\Http\FormRequest;
class ContactRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'message' => 'required',
'captcha' => ['required', new Captcha],
];
}
}
4. Then, in your controller action, you can use the validate
method to validate the request:
public function store(ContactRequest $request)
{
// The request is valid, so you can process the form data...
}
If the Captcha validation fails, the user will be redirected back to the form with an error message.