diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php b/src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php index 5d7047953115..320126366b73 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php @@ -26,9 +26,11 @@ public static function addGlobalScope($scope, $implementation = null) return static::$globalScopes[static::class][spl_object_hash($scope)] = $scope; } elseif ($scope instanceof Scope) { return static::$globalScopes[static::class][get_class($scope)] = $scope; + } elseif (is_string($scope) && class_exists($scope) && is_subclass_of($scope, Scope::class)) { + return static::$globalScopes[static::class][$scope] = new $scope; } - throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope.'); + throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope or be a class name of a class extending '.Scope::class); } /** diff --git a/tests/Database/DatabaseEloquentGlobalScopesTest.php b/tests/Database/DatabaseEloquentGlobalScopesTest.php index 7ae26071506d..a1bb15b3c4a1 100644 --- a/tests/Database/DatabaseEloquentGlobalScopesTest.php +++ b/tests/Database/DatabaseEloquentGlobalScopesTest.php @@ -43,6 +43,14 @@ public function testGlobalScopeCanBeRemoved() $this->assertEquals([], $query->getBindings()); } + public function testClassNameGlobalScopeIsApplied() + { + $model = new EloquentClassNameGlobalScopesTestModel; + $query = $model->newQuery(); + $this->assertSame('select * from "table" where "active" = ?', $query->toSql()); + $this->assertEquals([1], $query->getBindings()); + } + public function testClosureGlobalScopeIsApplied() { $model = new EloquentClosureGlobalScopesTestModel; @@ -190,6 +198,18 @@ public static function boot() } } +class EloquentClassNameGlobalScopesTestModel extends Model +{ + protected $table = 'table'; + + public static function boot() + { + static::addGlobalScope(ActiveScope::class); + + parent::boot(); + } +} + class ActiveScope implements Scope { public function apply(Builder $builder, Model $model)