rock3t
rock3t

Reputation: 2233

Is it possible to chain non-scope for model query?

Let me explain via example.

Model::staticMethod()->localScope()->get(); # works
Model::staticMethod()->nonStaticMethod()->get(); # fail

I'm a right to assume that your model methods have to be static and if you would like to chain more methods the following ones need to be local scope methods?

Let's say I want to have a query which chains 3 methods and the sequence is optional, meaning

Model::method1()->method2()->method3();
Model::method2()->method1()->method3();

How I would go about setting up my model?

Upvotes: 1

Views: 46

Answers (1)

E. Schalks
E. Schalks

Reputation: 101

You're correct, if the staticMethod starts a query you will only be able to use local scope methods from that point onwards. You can work around this by adding your own static methods to the Model class that actually return an instance of your Model so you can set it up from there. (Or use static methods like create() that already do this for you.)

The reason for this is that most static methods don't actually return an instance of the Model class but an instance of the Illuminate\Database\Eloquent\Builder class (https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Builder.html).

The Builder's __call() magic method intercepts all functions that don't actually exist on the Builder class, and then uses the function name to perform all kinds of magic.

In case you're interested, the code actually implementing the scopes is the following 3 lines in that __call method:

if (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
        return $this->callScope([$this->model, $scope], $parameters);
}

Upvotes: 1

Related Questions