Skip to content
Advertisement

Remove SoftDeletingScope as global scope

I am trying to remove the SoftDeletingScope as a global scope for a specific user role. So it should somehow look like this:

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

    if (Auth::check()) {
        // CPOs can see deleted users
        if (Auth::user()->hasRole('cpo')) {
            static::addGlobalScope('user-cpo-deleted', function(Builder $builder) {
                // 1
                $builder->withoutGlobalScope(IlluminateDatabaseEloquentSoftDeletingScope::class);
                // 2
                $builder->withoutGlobalScopes();
                // 3
                $builder->withTrashed();
                // 4
                $builder->where('id', '>=', 1);
            });
        }
    }
}

I tried solution 1-3 and, to make sure the method is called at all, 4. I logged the SQL queries and saw that 4 was called, but not the 3 before (to be precise, the methods did not remove the users.deleted_at is null part). I tried them separately and all together.

I know I can do something like this $users = User::withTrashed()->get();, which works, but that would be not entirely safe, because I would have to find every location where users could be queried and wrap that in an if statement.

Advertisement

Answer

I don’t know of easier solution than override bootSoftDeletes() from SoftDeletes trait with something like this:

public static function bootSoftDeletes()
{
    if (!Auth::check() || !Auth::user()->hasRole('cpo')) {
        static::addGlobalScope(new SoftDeletingScope);
    }
}

Adding and removing global scopes on the fly yields some wierd behaviour sometimes :/

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement