Laravel未定义变量 - 使用isset()

时间:2018-02-14 04:23:45

标签: php laravel-5

我正在与另一个问题的人合作:Laravel Return Siblings Results in Non-Object situation并且在实施他们的解决方案时,无论我多少次尝试处理错误,它都会失败。

在我的模型中,我有这个:

public function scopeFamily($query, $parentId) {
    if(isset($parentId)){
        return $query->where('user_id', auth()->id())->where(function ($query) {
            $query->where('parent_id', $parentId)
                  ->orWhere('reference_id', $parentId);
        });
    }
}

然后在刀片模板中,我用它来调用它:

if(isset($tasks->user->parent_id)){
    $parentId = $tasks->user->parent_id;
    if(isset($parentId)){
      $family =  App\Models\User::family($parentId)->get();
    }
}

我收到错误Undefined variable: parentId。应该不应该这样吗?我知道并非DB中的所有记录都有parent_id,但第一个isset()应该已经消除了这些记录。

1 个答案:

答案 0 :(得分:2)

在模型中使用use关键字。当我们必须访问闭包之外的变量时,需要使用use关键字来访问它们。

public function scopeFamily($query, $parentId) {
  if(isset($parentId)){
    return $query->where('user_id', auth()->id())->where(function ($query) use ($parentId){
        $query->where('parent_id', $parentId)
              ->orWhere('reference_id', $parentId);
    });
  }
}