scope

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:

  1. Create a class AbcScope that implements ScopeInterface
  2. 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):

  1. Create the scope
  2. Create a trait that will boot the scope and implement some handy methods
  3. 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!

It's only fair to share...Tweet about this on TwitterShare on RedditPin on PinterestShare on FacebookShare on Google+

Related Post

Tweaking Eloquent relations – how to get lat... Have you ever needed to show only single related model from the hasMany relationship on a set of parents? Being it latest, highest or just rand...
Querying relations in Laravel: get Models where la... Another part of Querying relations in Laravel will cover such problem: I want to get SomeModels that have latest RelatedModel (hasMany) matchin...
Laravel Searchable – the best package for el... In this first post of a series about https://github.com/jarektkaczyk/eloquence - the package that allows working with eloquent models in even simp...
Laravel – how to define and use Eloquent Glo... Laravel 4.2 introduced a new way of handling soft deletes by making use of traits and query builder macros wrapped in as a feature, that many people a...