Laravel中auth()->id()在Docker生产服务器返回null问题求助
问题解决思路
核心原因
本地环境队列用的是sync同步驱动,任务在当前请求进程里执行,能继承请求的认证上下文,所以auth()->id()能拿到值;而Docker生产环境用了异步队列驱动(比如Redis、Database),队列任务在独立进程中执行,没有请求的认证上下文,自然拿不到用户ID。
解决办法
不要在队列任务里获取用户ID,而是在请求上下文还存在的时候提前拿到,再传给队列任务:
- 修改中间件代码,提前获取用户ID并传入队列任务:
public function handle($request, Closure $next, $logType) { $response = $next($request); // 在请求进程内获取用户ID,此时认证上下文有效 $userId = auth()->id(); // 将用户ID作为参数传给队列任务 CreateLog::dispatch($request, $response, $logType, $userId)->onQueue(config('queue.queues.logging')); return $response; }
- 对应修改
CreateLog任务的构造函数和handle方法,接收并使用传入的$userId:
// CreateLog任务类 protected $request; protected $response; protected $logType; protected $userId; public function __construct($request, $response, $logType, $userId) { $this->request = $request; $this->response = $response; $this->logType = $logType; $this->userId = $userId; } public function handle() { // 直接使用$this->userId写入日志 // 示例:LogModel::create(['user_id' => $this->userId, ...]); }
额外注意
- 避免依赖队列任务继承请求上下文,异步队列进程和请求进程完全独立,任何需要的上下文数据都要显式传递。
- 检查生产环境的队列驱动配置,确认是否为异步驱动,这是触发问题的关键差异点。
内容的提问来源于stack exchange,提问作者Husniddin Tugizov
相关产品推荐
相关产品推荐

