Last active
May 19, 2019 17:18
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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