I need to apply a scope form a pivot class in a morphedByMany relationship included in a User class. This is the relationship:
public function nodes($nodeClass)
{
return
$this->morphedByMany(
$nodeClass,
'node',
'users_permissions',
'user_id',
'node_id',
'id',
'id'
)
->using('App\Models\UserNode');
}
Then, I have a role scope in the pivot class (UserNode). That scope is not our code, it is from HasRoles Traits from spatie/laravel-permission package:
public function scopeRole(Builder $query, $roles, $guard = null): Builder
{
if ($roles instanceof Collection) {
$roles = $roles->all();
}
if (! is_array($roles)) {
$roles = [$roles];
}
$roles = array_map(function ($role) use ($guard) {
if ($role instanceof Role) {
return $role;
}
$method = is_numeric($role) ? 'findById' : 'findByName';
$guard = $guard ?: $this->getDefaultGuardName();
return $this->getRoleClass()->{$method}($role, $guard);
}, $roles);
return $query->whereHas('roles', function ($query) use ($roles) {
$query->where(function ($query) use ($roles) {
foreach ($roles as $role) {
$query->orWhere(config('permission.table_names.roles').'.id', $role->id);
}
});
});
}
When I try to get specific class of nodes inside User class like this it works perfectly:
$nodes = $this->nodes($nodeClass)->get();
However, I don't know how I can apply properly the scope 'role' to the pivot class of the relation because wherePivot or wherePivotIn does not accept scopes, relations or closures. I have also tried other things with the same result like:
$nodes = $this->nodes($nodeClass)->whereHas('pivot', function($q) use ($roles) {
$q->role($roles);
})->get();
Is there any way to apply the pivot class' scope to this relation?
Thanks in advance