laravel 内的未定义变量 left join

Undefined variable inside laravel left join

在我的例子中,我想显示用户和每个用户完成的订单,订单有状态 我从输入表单中获取 $status 这是我的代码

$orders = DB::table('user_profiles')
        ->leftJoin('orders', function($join){
            $join->on('user_profiles.id','=','orders.id_user')
                ->where('orders.status','=',$status);
        })
        ->selectRaw('user_profiles.*, count(orders.id_user) as order_try_count')
        ->groupBy('user_profiles.id')
        ->orderBy('order_try_count',$order)
        ->paginate(15);

但是我得到未定义的变量状态,我应该怎么做才能解决这个问题?,谢谢

Yoo 需要使用 use 构造将变量传递到闭包中,如下所示:

->leftJoin('orders', function($join) use ($status) {

而不是

->leftJoin('orders', function($join) {

参考:anonymous functions

您必须使用 use() 方法在闭包中使用用户变量

尝试

->leftJoin('orders', function($join) use($status){
      $join->on('user_profiles.id','=','orders.id_user')
            ->where('orders.status','=',$status);
})