This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

Troiscent
Troiscent

Hello,

I would like to call scope inside another scope and I don't find the right syntax to use in the documentation.

Basically, I have a scopeDefault() function that does basic filtering (return published content only etc...)

I have another scopeFilters() that return content based on filters defined on $_GET element.

I would like to call the scopeDefault() scope inside the scopeFilters() scope, to do the basic filtering before adding more filters to the query.

I tried something like this :

$query->default()->where(......); // but I get an error

Tried also :

$query->scopeDefault()->where(....); // also return an error

I don't know what is the right syntax to call my scopeDefault() inside my scopeFilters() function, I'm new to laravel and october, if somebody with more experience can point me the right syntax, I would definitely appreciate.

Thanks

Alex

bayram4ik
bayram4ik

You can chain your scopes but if its not enough, you can pass parameters/conditions when calling scopes (eg. Dynamic Scopes https://laravel.com/docs/5.4/eloquent#local-scopes).

public function scopeStatus($query, $status = 'approved', $onlyMine = false, $due = null){
    $query->where('status_code', $status);
    if($onlyMine){
        $query->where('owner', 'admin');
    }
    if($due){
        $query->where('due', '<', $due);
    }
    return $query;
}

...then some where in Controller

$model->status('paid', true, \Carbon\Carbon::tomorrow());

In practice we try to keep our scopes clean and separated. Hope it helps.

Last updated

Troiscent
Troiscent

Hello,

Thank you for your answer, but I'm not sure it help me.

In your example, I can chain scope when I deal with the $model, but I need to add a scope to the $query (call a scope function directly in another scope function, not chaining scopes on a model).

I need that because I use the component provided by the Builder plugin to list my content, and that component have an option to apply a scope, but only one.

So I need a kind of scopeDefault() function, that apply all others scope I need (scopePublished(), scopeActive(), etc....)

Something like that

$query->published()->active()->etc...

on the $query element, not the $model.

Thanks

alxy
alxy

I think that this is not possible, as the scope recieves an instance of the QueryBuilder, not the Model. So you will have to call plain old where()s in your scope and do not have access to the other scope methods.

1-4 of 4

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.