Disable Global Scopes in Laravel Nova

May 17th, 2024 • 1 minute read time

If you're using global scopes in Laravel, these will likely affect your admin panel. Here's how to remove them.

Let's imagine we have a global scope that only shows content that is set to live.

class LiveScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        $builder->whereNotNull('live_at');
    }
}

If you apply this to a model globally, you'd register a scope like this.

class Course extends Model
{
    protected static function booted(): void
    {
        static::addGlobalScope(new LiveScope());
    }
}

As soon as you boot up Nova, you'll find that you won't be able to access (or see) these records since the global scope also applies to Nova resources.

There are a few ways to do this, but here's the easiest.

Nova's indexQuery method allows you to further chain on any Builder methods like you would elsewhere in your Laravel project. So, implementing it in the resource you need to disable scopes for would look like this.

class Course extends Resource
{
    public function indexQuery(NovaRequest $request, $query)
    {
        return $query->withoutGlobalScope(LiveScope::class);
    }
}

So, simply chain on withoutGlobalScope and provide the full namespace to the scope you want to disable for this resource.

You can also disable all global scopes if it's more convenient.

class Course extends Resource
{
    public function indexQuery(NovaRequest $request, $query)
    {
        return $query->withoutGlobalScopes();
    }
}

Load Nova back up, and you should now have a resource loaded without any global scopes applied!

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!

Table of contents

Tagged under