左联接中未定义的变量


Undefined variable inside laravel left join

在我的情况下,我想显示用户和每个用户完成的订单,订单有状态我从输入表单中获得$状态这是我的代码

$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) {

参考:匿名函数

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

尝试

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