-
resources/js/Pages/Contact.vue
Open in GitHub<template> // </template> <script> // export default { // beforeMount() { document.getElementById('captchaStyle').innerHTML=""; }, beforeUnmount() { document.getElementById('captchaStyle').innerHTML=".grecaptcha-badge { visibility: hidden !important; }"; }, // methods: { submit() { let submitForm = (token) => { this.fields.captcha_token = token; this.processing = true; this.success = false; this.errors = {}; axios.post('/contact', this.fields).then(response => { this.fields = {}; this.processing = false; this.success = true; }).catch(error => { this.processing = false; if (error.response.status === 422) { this.errors = error.response.data.errors || {}; } }); } grecaptcha .execute('6Ld2bfYdAAAAAL6yv0Oa-lRgw9y93KtIaXDdo20T', { action: "submit" }) .then (function (token) { submitForm(token); }); }, // }, } </script>
-
app/Rules/Recaptcha.php
Open in GitHubuse Illuminate\Contracts\Validation\Rule; use Illuminate\Support\Facades\Http; class Recaptcha implements Rule { // public function passes($attribute, $value) { if (config('app.env') === 'testing') { return true; } $response = Http::asForm()->post("https://www.google.com/recaptcha/api/siteverify", [ 'secret' => config('services.recaptcha.secret'), 'response' => $value ]); if ($response->successful() && $response->json('success') && $response->json('score') > 0.5) { return true; } return false; } public function message() { return 'Failed captcha validation.'; } }
-
app/Http/Controllers/PageController.php
Open in GitHubuse App\Mail\ContactFormSubmitted; use App\Rules\Recaptcha; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; use Inertia\Inertia; class PageController extends Controller { // public function contactFormSubmit(Request $request) { $this->validate($request, [ 'name' => 'required|string', 'email' => 'required|email', 'start' => 'required', 'type' => 'required', 'remote' => 'required', 'description' => 'required', 'captcha_token' => ['required', new Recaptcha] ]); Mail::to(config('mail.to.address'))->send(new ContactFormSubmitted($request)); return response()->json(null, 200); } // }