mpyw / laravel-local-class-scope
A tiny macro that reuse a global scope class as a local scope
Installs: 75 434
Dependents: 0
Suggesters: 0
Security: 0
Stars: 24
Watchers: 3
Forks: 2
Open Issues: 0
Requires
- php: ^8.0
- illuminate/database: ^9.0 || ^10.0 || ^11.0
- illuminate/support: ^9.0 || ^10.0 || ^11.0
Requires (Dev)
- orchestra/testbench: *
- orchestra/testbench-core: >=7.0
- phpunit/phpunit: >=9.5
README
A tiny macro that reuse a global scope class as a local scope.
The idea is from: [Proposal] Local query scopes as classes · Issue #636 · laravel/ideas
Requirements
- PHP:
^8.0
- Laravel:
^9.0 || ^10.0
Installing
composer require mpyw/laravel-local-class-scope
Usage
Simple Scope
class ActiveScope implements Scope { public function apply(Builder $query, Model $model): void { $query->where('active', true); } }
User::scoped(ActiveScope::class)->get();
User::scoped(new ActiveScope())->get();
Scope that takes arguments
class AgeScope implements Scope { protected $parameters; public function __construct(...$parameters) { $this->parameters = $parameters; } public function apply(Builder $query, Model $model): void { $query->where('age', ...$this->parameters); } }
User::scoped(AgeScope::class, '>', 18)->get();
User::scoped(new AgeScope('>', 18))->get();
Combination
User::scoped(ActiveScope::class)->scoped(AgeScope::class, '>', 18)->get();
Re-define as a local method scope
class User extends Model { public function scopeActive(Builder $query): Builder { return $this->scoped(ActiveScope::class); } }
Share local method re-definition via trait
trait ScopesActive { public function scopeActive(Builder $query): Builder { return $this->scoped(ActiveScope::class); } }
class User extends Model { use ScopesActive; }
class Admin extends Model { use ScopesActive; }