Laravel 10自定义中间件Request为空的问题排查求助
问题原因及解决方案
核心原因
你遇到的问题本质是HTTP重定向的参数丢失:
- 用户在
clientSecurity页面通过POST提交srvy_keycode,checkSecurity验证通过后执行redirect()->route('ClientSurvey'),这个重定向默认会发起GET请求。 - HTTP协议中,POST请求的参数不会自动传递到后续的GET重定向请求里,所以
ClientSurvey路由对应的GET请求中没有srvy_keycode参数,中间件自然无法从$request中获取。
解决方案
方案1:重定向时携带查询参数
修改checkSecurity方法中的重定向代码,将验证通过的code作为查询参数附加到目标路由:
public function checkSecurity(Request $request) { $validatedData = $request->validate([ 'srvy_keycode' => 'required' ]); $code = $validatedData['srvy_keycode']; $temporaryCode = ClientCode::where('code', $code)->first(); if ($temporaryCode) { // 携带参数重定向到GET路由 return redirect()->route('ClientSurvey', ['srvy_keycode' => $code]); } return back()->with('message', 'Error'); }
此时中间件中可以正常通过$request->input('srvy_keycode')获取参数,因为查询参数会被包含在Request的input数据中。
方案2:通过Session暂存参数(适合需要隐藏URL参数的场景)
如果不想在URL中暴露srvy_keycode,可以将参数暂存到Session中:
- 修改
checkSecurity方法,验证通过后存入Session:
public function checkSecurity(Request $request) { $validatedData = $request->validate([ 'srvy_keycode' => 'required' ]); $code = $validatedData['srvy_keycode']; $temporaryCode = ClientCode::where('code', $code)->first(); if ($temporaryCode) { session()->put('valid_srvy_code', $code); return redirect()->route('ClientSurvey'); } return back()->with('message', 'Error'); }
- 修改中间件代码,从Session中读取参数,并在验证后清理Session(避免重复使用):
public function handle(Request $request, Closure $next): Response { $code = $request->session()->get('valid_srvy_code'); // 检查Session中是否存在有效码 $temporaryCode = ClientCode::where('code', $code)->first(); if (!$temporaryCode) { return redirect()->route('clientSecurity')->with('message', 'Invalid code'); } // 验证通过后清理Session,防止重复使用 $request->session()->forget('valid_srvy_code'); return $next($request); }
注意:确保你的中间件注册在web中间件组中(Laravel默认web组包含StartSession中间件),否则无法访问Session。
排查要点
- 查看重定向后的浏览器地址栏:如果URL中没有
?srvy_keycode=xxx,说明参数确实没有被传递,这是问题的直接表现。 - 检查中间件注册位置:确认
checkcode别名在app/Http/Kernel.php的$middlewareGroups['web']中,或者在路由中单独调用时,确保Session相关中间件已执行。
内容的提问来源于stack exchange,提问作者Suelila John Anthony B.
相关产品推荐
相关产品推荐

