You need to enable JavaScript to run this app. Laravel租户识别中间件仅对部分JSON API路由生效问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Laravel租户识别中间件仅对部分JSON API路由生效问题排查

Laravel 中间件请求数据传递异常排查

问题概述

开发过程中使用Laravel框架搭配JSON API扩展包,需要从请求头中提取指定租户标识数据,解析完成后将对应租户信息传递到后续业务流程使用。目前发现同一路由组下,部分路由可以正常获取中间件注入的数据,另一部分路由获取到的合并数据完全为空。

现有实现代码

路由定义

JsonApi::register('default')
    ->authorizer('default')
    ->middleware('tenant.identifier')
    ->routes(function (RouteRegistrar $api) {
        $api->resource('categories')->readOnly();
    });

tenant.identifier 中间件核心逻辑

if (($sub = $request->header('X-Tenant-Identifier')) === null) {
    return new Response('Tenant identifier is missing from the request', Response::HTTP_BAD_REQUEST);
}

if (($tenant = Tenant::query()->where('subdomain', $sub)->first()) === null) {
    return new Response('Invalid tenant identifier', Response::HTTP_BAD_REQUEST);
}

$request->merge([
    'tenant' => $tenant,
    'requiresTenant' => true
]);

return $next($request);

异常表现

实际接口测试结果如下:

  • 访问/categories列表接口时,在业务逻辑中执行dd(request()->all()),可以正常看到所有合并注入的租户相关内容
  • 访问/categories/1单资源详情接口时,同样在业务逻辑中执行dd(request()->all()),返回值为空数组,完全没有之前合并的参数

已排查的替代实现方向

曾怀疑直接将租户数据合并到请求实例的实现方式不合理,尝试改用将租户实例绑定到应用容器的方式实现数据传递,参考代码为:

app()->instance(Tenant::class, $tenant);

但测试结果依然异常:

  • 中间件内部执行dd($tenant)可以确认租户数据已经成功从数据库查询解析完成
  • 后续业务流程从容器中读取绑定的租户实例时,获取到的值为空

待明确的核心问题

  1. 导致上述数据传递异常的根本原因是什么
  2. 多租户场景下,从请求头解析得到租户实例后,正确的跨环节数据传递实现方案是什么

内容的提问来源于stack exchange,提问作者user12789707

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.19 10:15:03