Skip to content

[12.x] Add NamedScope attribute #54450

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Mar 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/Illuminate/Database/Eloquent/Attributes/Scope.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Illuminate\Database\Eloquent\Attributes;

use Attribute;

#[Attribute(Attribute::TARGET_METHOD)]
class Scope
{
/**
* Create a new attribute instance.
*
* @param array|string $classes
* @return void
*/
public function __construct()
{
}
}
26 changes: 25 additions & 1 deletion src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Illuminate\Contracts\Support\CanBeEscapedWhenCastToString;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Database\ConnectionResolverInterface as Resolver;
use Illuminate\Database\Eloquent\Attributes\Scope as LocalScope;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\Concerns\AsPivot;
Expand All @@ -24,6 +25,7 @@
use JsonException;
use JsonSerializable;
use LogicException;
use ReflectionMethod;
use Stringable;

abstract class Model implements Arrayable, ArrayAccess, CanBeEscapedWhenCastToString, HasBroadcastChannel, Jsonable, JsonSerializable, QueueableEntity, Stringable, UrlRoutable
Expand Down Expand Up @@ -1639,7 +1641,8 @@ public function newPivot(self $parent, array $attributes, $table, $exists, $usin
*/
public function hasNamedScope($scope)
{
return method_exists($this, 'scope'.ucfirst($scope));
return method_exists($this, 'scope'.ucfirst($scope)) ||
static::isScopeMethodWithAttribute($scope);
}

/**
Expand All @@ -1651,9 +1654,26 @@ public function hasNamedScope($scope)
*/
public function callNamedScope($scope, array $parameters = [])
{
if ($this->isScopeMethodWithAttribute($scope)) {
return $this->{$scope}(...$parameters);
}

return $this->{'scope'.ucfirst($scope)}(...$parameters);
}

/**
* Determine if the given method has a scope attribute.
*
* @param string $method
* @return bool
*/
protected static function isScopeMethodWithAttribute(string $method)
{
return method_exists(static::class, $method) &&
(new ReflectionMethod(static::class, $method))
->getAttributes(LocalScope::class) !== [];
}

/**
* Convert the model instance to an array.
*
Expand Down Expand Up @@ -2377,6 +2397,10 @@ public function __call($method, $parameters)
*/
public static function __callStatic($method, $parameters)
{
if (static::isScopeMethodWithAttribute($method)) {
$parameters = [static::query(), ...$parameters];
}

return (new static)->$method(...$parameters);
}

Expand Down
19 changes: 17 additions & 2 deletions tests/Integration/Database/EloquentModelScopeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Illuminate\Tests\Integration\Database;

use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Attributes\Scope as NamedScope;
use Illuminate\Database\Eloquent\Model;

class EloquentModelScopeTest extends DatabaseTestCase
Expand All @@ -19,12 +21,25 @@ public function testModelDoesNotHaveScope()

$this->assertFalse($model->hasNamedScope('doesNotExist'));
}

public function testModelHasAttributedScope()
{
$model = new TestScopeModel1;

$this->assertTrue($model->hasNamedScope('existsAsWell'));
}
}

class TestScopeModel1 extends Model
{
public function scopeExists()
public function scopeExists(Builder $builder)
{
return $builder;
}

#[NamedScope]
protected function existsAsWell(Builder $builder)
{
return true;
return $builder;
}
}
36 changes: 36 additions & 0 deletions tests/Integration/Database/EloquentNamedScopeAttibuteTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Illuminate\Tests\Integration\Database;

use Orchestra\Testbench\Attributes\WithMigration;
use Orchestra\Testbench\TestCase;

#[WithMigration]
class EloquentNamedScopeAttibuteTest extends TestCase
{
protected $query = 'select * from "named_scope_users" where "email_verified_at" is not null';

protected function setUp(): void
{
parent::setUp();

$this->markTestSkippedUnless(
$this->usesSqliteInMemoryDatabaseConnection(),
'Requires in-memory database connection',
);
}

public function test_it_can_query_named_scoped_from_the_query_builder()
{
$query = Fixtures\NamedScopeUser::query()->verified(true);

$this->assertSame($this->query, $query->toRawSql());
}

public function test_it_can_query_named_scoped_from_static_query()
{
$query = Fixtures\NamedScopeUser::verified(true);

$this->assertSame($this->query, $query->toRawSql());
}
}
38 changes: 38 additions & 0 deletions tests/Integration/Database/Fixtures/NamedScopeUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Illuminate\Tests\Integration\Database\Fixtures;

use Illuminate\Database\Eloquent\Attributes\Scope as NamedScope;
use Illuminate\Database\Eloquent\Builder;

class NamedScopeUser extends User
{
/** {@inheritdoc} */
#[\Override]
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}

#[NamedScope]
protected function verified(Builder $builder, bool $email = true)
{
return $builder->when(
$email === true,
fn ($query) => $query->whereNotNull('email_verified_at'),
fn ($query) => $query->whereNull('email_verified_at'),
);
}

public function scopeVerifiedUser(Builder $builder, bool $email = true)
{
return $builder->when(
$email === true,
fn ($query) => $query->whereNotNull('email_verified_at'),
fn ($query) => $query->whereNull('email_verified_at'),
);
}
}
Loading