Laravel未定义变量-使用isset() [英] Laravel Undefined Variable - Using isset()

查看:931
本文介绍了Laravel未定义变量-使用isset()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正与其他人一起处理另一个问题: Laravel返回兄弟姐妹出现非对象情况,并且在实施解决方案时都会失败,无论我尝试错误处理多少次.

I was working with someone on this other question: Laravel Return Siblings Results in Non-Object situation and in implementing their solution it fails regardless of how many times I try error handling.

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

In my model I have this:

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);
        });
    }
}

然后在刀片模板中,我使用此名称进行调用:

Then in the blade template I am calling it using this:

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

我收到错误Undefined variable: parentId.那应该不可能吗?我知道不是数据库中的所有记录都具有parent_id,但是第一个isset()应该已经消除了这些记录.

I get the error Undefined variable: parentId. That shouldn't be possible should it? I know not all records in the DB have a parent_id, but the first isset() should have eliminated those.

推荐答案

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

In model use use keyword. When we have to access the variable which is outside of the closure, need to use use keyword to access those.

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);
    });
  }
}

这篇关于Laravel未定义变量-使用isset()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆