If you are looking for an example of Eloquent Global Scope feature, then you’re in the right place!
Check the ready-to-use demo at …
https://github.com/jarektkaczyk/laravel5-global-scope-example
UPDATE – I have just created an abstract GlobalScope
class that deals with removing
the scope constraints for you. That being said, you have to implement only the apply
method in the scope class if you use my package, and all the heavy lifting will be done for you.
Here it is: sofa/laravel-global-scope
Applying global scope requires just 2 simple steps:
- Create a class
AbcScope
that implementsScopeInterface
- Boot that class in your Eloquent model calling
static::addGlobalScope(new AbcScope)
So basically you could just create the scope and then boot it in the model, which should use the scope.
However this is not going to be very reusable, so instead let’s take a bit longer path (and this is how SoftDeleting
is implemented in the Eloquent core):
- Create the scope
- Create a trait that will boot the scope and implement some handy methods
- Add single
use AbcTrait
line to all the models that will use the scope
As an example let’s use Post
with draft/published feature. By default we would like to get only published posts, but when we are logged in to the admin area, we need to see also the drafts:
(In real life I would use whereNull('published_at')
as a constraint, however this would be exactly the same as SoftDeletingTrait
, so instead I’m gonna check for published=1
condition, for this is a bit trickier)
Usage
1. Apply the scope for the Post
model:
2. Use it:
And that’s all!