Skip to content

Instantly share code, notes, and snippets.

@jbeales
Last active May 19, 2019 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbeales/c6e21e621def6c2dd630ec9d15a23891 to your computer and use it in GitHub Desktop.
Save jbeales/c6e21e621def6c2dd630ec9d15a23891 to your computer and use it in GitHub Desktop.
A trait that makes it easier to remove Global Scopes from Laravel models. See https://johnbeales.com/2019/remove-model-global-scopes-laravel-nova/ for details.
<?php
namespace App\Concerns;
use Closure;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Arr;
trait HasRemovableGlobalScopes {
/**
* @param \Illuminate\Database\Eloquent\Scope|string $scope
*/
public static function withoutGlobalScope( $scope )
{
if (is_string($scope) && is_array(static::$globalScopes[static::class])) {
Arr::forget(static::$globalScopes[static::class], $scope);
} elseif ($scope instanceof Closure) {
Arr::forget(static::$globalScopes[static::class], spl_object_hash($scope));
} elseif ($scope instanceof Scope) {
Arr::forget(static::$globalScopes[static::class], get_class($scope));
}
}
/**
* @param \Illuminate\Database\Eloquent\Scope[]|string[] $scopes
*/
public static function withoutGlobalScopes( array $scopes = [])
{
if(empty($scopes)) {
static::$globalScopes = [];
} else {
foreach($scopes as $scope) {
static::withoutGlobalScope($scope);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment