FaFi's avatar
Level 1

Remove Global Scope in boot method

Hello my friends,

I have a problem that I want to solve but I can not figure out. First of all I would like to mention that I use Laravel 5.5 version. Here is the issue ;

<?php
class Product extends Model{

   use WithPassive, WithPrivate;

   public static function boot(){
       parent::boot();

       parent::observe( ProductObserver::class );
   }

}

My model file is above. As shown in the model file, there are 2 GlobalScope traits. These are added as defaults.

   SELECT * FROM `products` WHERE `products`.'is_public' = 1 AND `products`.'is_private' = 0

What I want to do is remove these global scopes according to a certain criterion.

<?php
public static function boot(){
       parent::boot();

       static::addGlobalScope('xxx', function(Builder $builder){
           if(...){
               $builder->withoutGlobalScopes([
                   ActiveScope::class,
                   PublicScope::class,
               ]);
           }
       });

       parent::observe( ProductObserver::class );
   }

When I dump the builder, the related global scope is deleted, though it is not actually deleted.

<?php
   dump(Products::toSql());

Unfortunately, when I run the command, the global scope is still in place. I would ask your assistance in this matter.

0 likes
8 replies
shez1983's avatar

perhaps you can remove this through a controller/services/repository

where you have a function lets say

{

if ( $removeGlobalScopes) {
    Product::withoutGlobalScopes()->all();
} 
else
{
///
}
}
FaFi's avatar
Level 1

@shez1983 thank you for the answer. but I do not want to do it in a controller or similar place.

i do not understand, why i can not delete any global scope in the global scope? appears to be deleted, it does not seem to be actually deleted when the query is run.

FaFi's avatar
FaFi
OP
Best Answer
Level 1

i created a new global scope. i changed the order of adding global scope to model class. it worked like this. but it didn’t seem to me right to a solution.

shez1983's avatar

if a scope isnt applied in EVERY CASE then really it shouldnt be a global scope.. you could relegate it to a local scope which you call when needed.

FaFi's avatar
Level 1

@shez1983 i'm trying to do it with global scope because it's something that needs to be applied consistently.

it seems that the apparent problem does not have a proper answer. for the moment i have solved it by the way i have written above.

mindz's avatar
   protected static function boot()
    {
        parent::boot();
        unset(static::$globalScopes[static::class][RemovedGlobalScope::class]);
        static::addGlobalScope(new GlobalScope());
    }
5 likes
Inserve's avatar

I see no replies, but the unset() line actually worked in my case. Thanks!

Please or to participate in this conversation.