Armani's avatar
Level 17

Checking user type before applying the global scope

I created a global scope by running this command:

php artisan make:scope BranchScope

And the logic it like this:

public function apply(Builder $builder, Model $model): void
{
    $builder->where('branch_id', auth()->user()->branch_id);
}

then applied to the model like this:

#[ScopedBy(BranchScope::class)]

and everything works fine but I want to apply the scope only for regular users not for admin.

so I created a local scope like this:

public function scopeAdmin(Builder $query): void
{
  if(auth()->user()->isAdmin)
  {
      $query->withoutGlobalScopes();
  }
}

and Added to the query like this:

Item::query()->admin()->get();

and it works but I want to know, is there a better way to do it?

0 likes
5 replies
tisuchi's avatar

@armani I may go with middleware instead of scope here.

Based on the user types/rights, I may enable or disable certain scopes.

tisuchi's avatar

@Armani This is what is in my mind.

public function handle($request, Closure $next)
{
    if (auth()->check() && auth()->user()->isAdmin) {
        SomeModel::withoutGlobalScopes(BranchScope::class);
        // more logic...
    }

    return $next($request);
}
1 like
Armani's avatar
Level 17

@tisuchi I added an if statement and it fixed:

public function apply(Builder $builder, Model $model): void
{
    if(!auth()->user()->isAdmin)
	{
		$builder->where('branch_id', auth()->user()->branch_id);
	}
}
krisi_gjika's avatar

why not just Item::query()->withoutGlobalScopes()->get(); where you know only admin can access

1 like

Please or to participate in this conversation.