FaFi
2 years ago
1246
6
Eloquent

Remove Global Scope in boot method

Posted 2 years ago by FaFi

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.

Please sign in or create an account to participate in this conversation.