diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php b/src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php index 320126366b73..7e3745f123a9 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php @@ -33,6 +33,23 @@ public static function addGlobalScope($scope, $implementation = null) throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope or be a class name of a class extending '.Scope::class); } + /** + * Register multiple global scopes on the model. + * + * @param array $scopes + * @return void + */ + public static function addGlobalScopes(array $scopes) + { + foreach ($scopes as $key => $scope) { + if (is_string($key)) { + static::addGlobalScope($key, $scope); + } else { + static::addGlobalScope($scope); + } + } + } + /** * Determine if a model has a global scope. * diff --git a/tests/Database/DatabaseEloquentGlobalScopesTest.php b/tests/Database/DatabaseEloquentGlobalScopesTest.php index a1bb15b3c4a1..bef11fbcc854 100644 --- a/tests/Database/DatabaseEloquentGlobalScopesTest.php +++ b/tests/Database/DatabaseEloquentGlobalScopesTest.php @@ -59,6 +59,14 @@ public function testClosureGlobalScopeIsApplied() $this->assertEquals([1], $query->getBindings()); } + public function testGlobalScopesCanBeRegisteredViaArray() + { + $model = new EloquentGlobalScopesArrayTestModel; + $query = $model->newQuery(); + $this->assertSame('select * from "table" where "active" = ? order by "name" asc', $query->toSql()); + $this->assertEquals([1], $query->getBindings()); + } + public function testClosureGlobalScopeCanBeRemoved() { $model = new EloquentClosureGlobalScopesTestModel; @@ -210,6 +218,21 @@ public static function boot() } } +class EloquentGlobalScopesArrayTestModel extends Model +{ + protected $table = 'table'; + + public static function boot() + { + static::addGlobalScopes([ + 'active_scope' => new ActiveScope, + fn ($query) => $query->orderBy('name'), + ]); + + parent::boot(); + } +} + class ActiveScope implements Scope { public function apply(Builder $builder, Model $model)