thewebartisan7's avatar

Load scope class not globally

As explained here: https://laravel.com/docs/5.7/eloquent#query-scopes I create my class that implement Scope interface.

In docs is only mention how to load them globally, using: static::addGlobalScope(new AgeScope);

But how I can load the scope class on demand?

thanks

0 likes
10 replies
thewebartisan7's avatar

@staudenmeir thanks, I see local scope, but this is only for methods inside model class. I would like to call on demand the Scope class object and not method scopeMyscop()

thewebartisan7's avatar

I see local scope go in model like this:

public function scopePopular($query)
{
    return $query->where('votes', '>', 100);
}

and then can be called like Model::popular()

But what I want is to create a Scope class like example in docs AgeScope

But how to call this class on demand like method-scopes of model?

Can you just explain how to call for example AgeScope example in docs? Because they show only how to load it globally like:

static::addGlobalScope(new AgeScope);

thewebartisan7's avatar

I would like something like:

User::addScope(new AgeScope)->all();

Vilfago's avatar

If I take the popular example, you can do : User::select('id', 'name')->popular()->get()

thewebartisan7's avatar

@vilfago yes I understand how to do for popular and other local scope like scopePopular..

But how to call a class like AgeScope without using addGlobalScope() but calling on demand?

thewebartisan7's avatar

I think that I found checking in Model class, I found withGlobalScope() method, not sure if this is right one, need to test. But seem that allow to load Scope class like AgeScope without using addGlobalScope()


    /**
     * Register a new global scope.
     *
     * @param  string  $identifier
     * @param  \Illuminate\Database\Eloquent\Scope|\Closure  $scope
     * @return $this
     */
    public function withGlobalScope($identifier, $scope)
    {
        $this->scopes[$identifier] = $scope;

        if (method_exists($scope, 'extend')) {
            $scope->extend($this);
        }

        return $this;
    }

thewebartisan7's avatar

I found that below code work fine, but not sure if is correct way since I don't find anything on docs or via google.




    $sql = User::query()
        ->withGlobalScope('visibility', new VisibilityScope())
        ->limit(100)
        ->toSql();

    dd($sql);


output:

select * from users where visibility in (?, ?) limit 100

1 like
MrPunyapal's avatar

@thewebartisan7 Yeah it's been years but you can use like this.

User::query()
	->tap(new VisibilityScope())
	->limit(100)
    ->toSql();

Please or to participate in this conversation.