Laravel中间件中获取请求方法(GET、POST等)的实现方案
获取Laravel请求方法用于日志记录的解决方案
嘿,你完全不用绕到$request->route()里去,Laravel的Request实例本身就提供了非常直接的方法来获取请求的HTTP方法名,正好适配你的日志需求。
直接获取请求方法的方式
你可以任选以下两种方法之一:
$request->method():返回大写的HTTP方法名(比如GET、POST、DELETE),这是Laravel封装的便捷方法$request->getMethod():这是Symfony Request类的原生方法,同样返回大写的方法名
修改你的中间件代码
下面是加入了请求方法日志记录的完整代码示例:
use Illuminate\Support\Facades\Log; public function handle($request, Closure $next) { // 获取当前请求的HTTP方法 $httpMethod = $request->method(); $api_key = $request->headers->get('x-api-key'); if($api_key != $this->auth_key){ // 将请求方法加入未授权访问的日志 Log::warning('Unauthorized API access attempt', [ 'request_method' => $httpMethod, 'reason' => "You're not authorized to access. Make sure that you're passing your API Key" ]); return $this->response->unauthorize( "You're not authorized to access. Make sure that you're passing your API Key" ); } // 记录合法请求的方法信息 Log::info('Valid API request processed', [ 'request_method' => $httpMethod, 'api_key_prefix' => substr($api_key, 0, 4) // 敏感信息脱敏,只记录前缀 ]); return $next($request); }
额外小提示
- 如果你需要判断请求是否为特定方法,可直接用
$request->isMethod('POST')这类语法,非常便捷 - 日志中涉及敏感信息(比如完整API Key)时,一定要做脱敏处理,避免泄露安全风险
内容的提问来源于stack exchange,提问作者Hassan Raza
相关产品推荐
相关产品推荐

