Skip to content

Commit 0049bc2

Browse files
authored
[10.x] add addGlobalScopes method (#49880)
1 parent a050fb5 commit 0049bc2

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/Illuminate/Database/Eloquent/Concerns/HasGlobalScopes.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,23 @@ public static function addGlobalScope($scope, $implementation = null)
3333
throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope or be a class name of a class extending '.Scope::class);
3434
}
3535

36+
/**
37+
* Register multiple global scopes on the model.
38+
*
39+
* @param array $scopes
40+
* @return void
41+
*/
42+
public static function addGlobalScopes(array $scopes)
43+
{
44+
foreach ($scopes as $key => $scope) {
45+
if (is_string($key)) {
46+
static::addGlobalScope($key, $scope);
47+
} else {
48+
static::addGlobalScope($scope);
49+
}
50+
}
51+
}
52+
3653
/**
3754
* Determine if a model has a global scope.
3855
*

tests/Database/DatabaseEloquentGlobalScopesTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,14 @@ public function testClosureGlobalScopeIsApplied()
5959
$this->assertEquals([1], $query->getBindings());
6060
}
6161

62+
public function testGlobalScopesCanBeRegisteredViaArray()
63+
{
64+
$model = new EloquentGlobalScopesArrayTestModel;
65+
$query = $model->newQuery();
66+
$this->assertSame('select * from "table" where "active" = ? order by "name" asc', $query->toSql());
67+
$this->assertEquals([1], $query->getBindings());
68+
}
69+
6270
public function testClosureGlobalScopeCanBeRemoved()
6371
{
6472
$model = new EloquentClosureGlobalScopesTestModel;
@@ -210,6 +218,21 @@ public static function boot()
210218
}
211219
}
212220

221+
class EloquentGlobalScopesArrayTestModel extends Model
222+
{
223+
protected $table = 'table';
224+
225+
public static function boot()
226+
{
227+
static::addGlobalScopes([
228+
'active_scope' => new ActiveScope,
229+
fn ($query) => $query->orderBy('name'),
230+
]);
231+
232+
parent::boot();
233+
}
234+
}
235+
213236
class ActiveScope implements Scope
214237
{
215238
public function apply(Builder $builder, Model $model)

0 commit comments

Comments
 (0)