Skip to content

Commit

Permalink
[10.x] add addGlobalScopes method (#49880)
Browse files Browse the repository at this point in the history
  • Loading branch information
emargareten authored Jan 29, 2024
1 parent a050fb5 commit 0049bc2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
23 changes: 23 additions & 0 deletions tests/Database/DatabaseEloquentGlobalScopesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 0049bc2

Please sign in to comment.