Laravel集成Recaptcha v3的联系表单无法触发后端方法问题
Laravel集成Recaptcha v3联系表单提交异常问题
问题现象
在Laravel项目中搭建集成Recaptcha v3的联系表单时,给提交按钮添加data-action="sendmail"属性后,后端的store方法完全无法触发;移除该属性后,表单可正常提交,能看到echo的测试信息,邮件也能正常发送。
相关代码
表单代码
<form action="{{action('App\Http\Controllers\ContactController@store')}}" method="POST" id="contactForm"> @csrf <div class="flex flex-col p-10"> <label for="name" class="font-poppins text-sb-teagreen text-xl">{{__('Name')}}</label> <input type="text" name="name" id="name" class="border-2 border-sb-teagreen p-2"> <label for="email" class="font-poppins text-sb-teagreen text-xl">{{__('Email')}}</label> <input type="email" name="email" id="email" class="border-2 border-sb-teagreen p-2"> <label for="message" class="font-poppins text-sb-teagreen text-xl">{{__('Message')}}</label> <textarea name="message" id="message" cols="30" rows="10" class="border-2 border-sb-teagreen p-2"></textarea> <button data-sitekey="{{ config('services.recaptcha.site_key') }}" data-callback='onSubmit' data-action="sendmail" type="submit" class="g-recaptcha bg-sb-teagreen text-white font-poppins text-xl p-2 mt-4">{{__('Send')}}</button> @if(session('message')) <div class="text-center bg-sb-teagreen text-white p-2 mb-2">{{ session('message') }}</div> @endif </div> </form> @push('scripts') <script> function onSubmit(token) { document.getElementById("contactForm").submit(); } </script> @endpush
路由代码
Route::get('/contact', 'App\Http\Controllers\FrontendController@contact')->name('contact'); Route::post('/contactformulier', 'App\Http\Controllers\ContactController@store')->name('sendmail');
控制器代码
public function store(Request $request) { echo('test store function'); $request->validate([ 'name' => 'required', 'email' => 'required|email', 'message' => 'required', 'g-recaptcha-response' => ['required', new ReCaptcha] ]); $data = request()->all(); Mail::to('**************')->send(new Contact($data)); return redirect()->route('contact')->with('message', 'Thanks for your message. We\'ll be in touch.'); }
排查与解决建议
确认Recaptcha v3脚本已正确引入
目前代码中未看到Recaptcha v3的官方脚本,这是关键缺失项。必须在页面头部或尾部引入:<script src="https://www.google.com/recaptcha/api.js?render={{ config('services.recaptcha.site_key') }}"></script>仅靠按钮的
g-recaptcha类,带data-action时可能无法正确加载验证逻辑,导致回调函数不触发。修改按钮类型避免提交冲突
按钮当前是type="submit",会触发原生表单提交,加上Recaptcha回调后容易出现冲突。改成type="button",完全由Recaptcha验证通过后的回调触发提交:<button data-sitekey="{{ config('services.recaptcha.site_key') }}" data-callback='onSubmit' data-action="sendmail" type="button" class="g-recaptcha bg-sb-teagreen text-white font-poppins text-xl p-2 mt-4">{{__('Send')}}</button>检查Recaptcha验证规则逻辑
添加data-action后,Recaptcha会生成包含该action的验证响应。如果自定义的ReCaptcha验证规则中对action做了校验,需确保规则内的action值与data-action="sendmail"一致。可以临时注释掉g-recaptcha-response的验证规则,测试是否能触发store方法,以此确认是否是验证规则阻塞了请求。改用路由名称生成表单Action
当前表单action用action()生成URL,改用路由名称更可靠,避免控制器命名空间变化导致的错误:<form action="{{ route('sendmail') }}" method="POST" id="contactForm">
内容的提问来源于stack exchange,提问作者color
相关产品推荐
相关产品推荐

