访问Laravel(PHP)中匿名函数中的范围外变量

访问Laravel(PHP)中匿名函数中的范围外变量,php,mysql,laravel,anonymous-function,laravel-eloquent,Php,Mysql,Laravel,Anonymous Function,Laravel Eloquent,我想在Laravel中为相关表添加种子。我在访问匿名函数中的超出范围变量时遇到问题,我为whereHas方法定义了该函数,以便在我的has查询中放置“where”条件 $id=$user->id;//范围外变量 $posts=Post::whereHas('comments',function($query){ $query->where('user\u id',$id); })->get(); 从技术上讲,我无法访问匿名函数中的$id 这不是一个拉威尔问题,而是一个PHP问题。只需在参数列表

我想在Laravel中为相关表添加种子。我在访问匿名函数中的超出范围变量时遇到问题,我为
whereHas
方法定义了该函数,以便在我的has查询中放置“where”条件

$id=$user->id;//范围外变量
$posts=Post::whereHas('comments',function($query){
$query->where('user\u id',$id);
})->get();

从技术上讲,我无法访问匿名函数中的
$id

这不是一个拉威尔问题,而是一个PHP问题。只需在参数列表后添加
use($variable)

$posts = Post::whereHas('comments', function ($query) use ($id) {
    $query->where('user_id', $id);
})->get();