Skip to content

Commit 26676d8

Browse files
authored
[13.x] Fix scopedBy attribute not following inheritance chain (#57213)
* Fix scopedBy attribute not following inheritance * Works for both traits and direct inheritance * Adding test * Code style
1 parent f4fe15f commit 26676d8

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Illuminate\Support\Arr;
99
use Illuminate\Support\Collection;
1010
use InvalidArgumentException;
11+
use ReflectionAttribute;
1112
use ReflectionClass;
1213

1314
trait HasGlobalScopes
@@ -31,8 +32,13 @@ public static function resolveGlobalScopeAttributes()
3132
{
3233
$reflectionClass = new ReflectionClass(static::class);
3334

34-
return (new Collection($reflectionClass->getAttributes(ScopedBy::class)))
35-
->map(fn ($attribute) => $attribute->getArguments())
35+
$attributes = (new Collection($reflectionClass->getAttributes(ScopedBy::class, ReflectionAttribute::IS_INSTANCEOF)));
36+
37+
foreach ($reflectionClass->getTraits() as $trait) {
38+
$attributes->push(...$trait->getAttributes(ScopedBy::class, ReflectionAttribute::IS_INSTANCEOF));
39+
}
40+
41+
return $attributes->map(fn ($attribute) => $attribute->getArguments())
3642
->flatten()
3743
->all();
3844
}

tests/Database/DatabaseEloquentGlobalScopesTest.php

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

63+
public function testGlobalScopeInInheritedAttributeIsApplied()
64+
{
65+
$model = new EloquentGlobalScopeInInheritedAttributeTestModel;
66+
$query = $model->newQuery();
67+
$this->assertSame('select * from "table" where "active" = ?', $query->toSql());
68+
$this->assertEquals([1], $query->getBindings());
69+
}
70+
6371
public function testClosureGlobalScopeIsApplied()
6472
{
6573
$model = new EloquentClosureGlobalScopesTestModel;
@@ -267,3 +275,16 @@ public function apply(Builder $builder, Model $model)
267275
return $builder->where('active', 1);
268276
}
269277
}
278+
279+
#[ScopedBy(ActiveScope::class)]
280+
trait EloquentGlobalScopeInInheritedAttributeTestTrait
281+
{
282+
//
283+
}
284+
285+
class EloquentGlobalScopeInInheritedAttributeTestModel extends Model
286+
{
287+
use EloquentGlobalScopeInInheritedAttributeTestTrait;
288+
289+
protected $table = 'table';
290+
}

0 commit comments

Comments
 (0)