You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel框架的withCount()函数中传入额外自定义变量?

问题原因

该报错是PHP闭包(匿名函数)的作用域限制导致的:默认状态下闭包内部无法直接访问父作用域中定义的$date_from、$date_to变量,需要手动将外部变量导入闭包作用域。

解决方法

在闭包声明后通过use关键字引入需要用到的外部变量即可,修改后的代码如下:

$date_from = Carbon::now()->subDays(1825);
$date_to = Carbon::now()->subDays($days);

return Inventory::where('inventory.client_id', $user->client_id)
                  ->withCount(["sellRecord as last_sale_date"  => function($query) use ($date_from, $date_to) {
                      $query->select(DB::raw("created_at"))
                            ->latest()
                            ->whereBetween('created_at', [$date_from, $date_to])
                            ->take(1);
                  }])
                  ->paginate(100);

如果你使用的是PHP 7.4及以上版本,也可以用箭头函数简化写法,无需手动写use导入变量,箭头函数会自动捕获父作用域的变量:

return Inventory::where('inventory.client_id', $user->client_id)
                  ->withCount(["sellRecord as last_sale_date"  => fn($query) => 
                      $query->select(DB::raw("created_at"))
                            ->latest()
                            ->whereBetween('created_at', [$date_from, $date_to])
                            ->take(1)
                  ])
                  ->paginate(100);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:06:03