我正与其他人一起处理另一个问题: 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未定义变量
发布评论