Reputation: 2086
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();
}
}
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.
Upvotes: 1
Views: 513
Reputation: 34914
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);
});
}
}
Upvotes: 3