How to add default query condition on model

Hy

I know that in my plugin model i can add function newQuery exp:

public function newQuery($excludeDeleted = true) {
      return parent::newQuery($excludeDeleted)
                ->where('xxx', '=', yyy);
    }

to aplly default condition on all model query, but i want to know how can i override an other plugin model to do that.

Thanks

Hello

anyone have any idea?

Hi @ridha82 ,

Inside your Plugin.php file, you can do something like :

public function boot()
{
    \Vendor\Plugin\Models\SomeModel::extend(function ($model) {
        $model::addGlobalScope('onlyActive', function ($builder) {
            $builder->where('is_active', true); // Example condition
        });
    });
}

Remove one scope

\Vendor\Plugin\Models\SomeModel::withoutGlobalScope('onlyActive')->get();

Remove all of the global scopes…

\Vendor\Plugin\Models\SomeModel::withoutGlobalScopes()->get();

Hi @apinard

It works

Thanks

1 Like