vincent15000's avatar

ScopedBy not working ? => timeout

Hello,

I have added this code.

#[ObservedBy([UserObserver::class])]
#[ScopedBy([CompanyScope::class])]
class User extends Authenticatable implements MustVerifyEmail
{
	...
}

With this scope.

class CompanyScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     */
    public function apply(Builder $builder, Model $model): void
    {
        $builder->where('company_id', auth()->user()->company_id);
    }
}

Here is the query from the controller.

$users = User::
    with('image', 'company')
    ->where(function ($query) {
        $query
            ->where('role', '!=', RoleEnum::SUPERADMIN)
            ->orWhereNull('role');
    })
    ->orderBy('name')
    ->get();

I get a timeout error.

What am I doing wrong ?

Thanks for your help.

V

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

Infinite loop... because the Scope class depends on the authenticated user, which is scoped using this Scope class, which depends on the authenticated user, which is scoped using this Scope class.... and so on...

1 like
vincent15000's avatar

@tykus Hmmm ... so how to define my scope ? I need to retrieve the company_id for the connected user.

Where is the problem ? It's because I'm using auth()->user() in a scope applied on the User class ?

Do you mean that the same scope applied on another class would work ?

tykus's avatar

@vincent15000

Where is the problem ? It's because I'm using auth()->user() in a scope applied on the User class ?

Yes, I believe so.

Do you mean that the same scope applied on another class would work ?

Yes. I mean, the scope is (probably) working, but it is caught in an infinite loop.

I think you will need to override the EloquentUserProvider to explicitly remove the Scope from the query that retrieves the User (i.e. retrieveById)

1 like

Please or to participate in this conversation.