Last active
September 22, 2016 09:55
-
-
Save sgelbart/781f6d483601d2a5efd8 to your computer and use it in GitHub Desktop.
Any easy implementation for laravel in-model global scopes (basic testing in Laravel 4.2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * EASY SCOPE GLOBAL | |
| * | |
| * by Sabrina Gelbart | |
| * Note: has not been thoroughly tested! | |
| * To use, include this trait in your models | |
| * then override the scopeGlobal method in your Model | |
| * to UNDO the scope use syntax User::noEasyGlobal()->where(.. | |
| * (noEasyGlobal must be called STATICALLY, so User::where(...)->noEasyGlobal() WONT WORK) | |
| **/ | |
| trait easyGlobalScope(){ | |
| /** | |
| * @param $query | |
| * @return mixed | |
| */ | |
| public function scopeGlobal($query) | |
| { | |
| return $query; | |
| } | |
| /** | |
| * Override all newQuery instances | |
| * | |
| * @return mixed | |
| */ | |
| public function newQuery () | |
| { | |
| return parent::newQuery()->global(); | |
| } | |
| /** | |
| * This method overrides all the global scopes | |
| * MUST BE CALLED STATICALLY | |
| * E.g., User::noEasyGlobal()->where(... will work. User::where(..)->noEasyGlobal() will NOT work! | |
| * | |
| * This needs to be a static method which just wraps the non-static newQueryNoEasyGlobal (might be better way to do this) | |
| * | |
| * @return mixed | |
| */ | |
| public static function noEasyGlobal() | |
| { | |
| $instance = new Static; | |
| return $instance->newQueryNoEasyGlobal(); | |
| } | |
| /** | |
| * Return newQuery without global scope | |
| * Note: this WILL use any other scopes applied Laravel's traditional way | |
| * | |
| * @return mixed | |
| */ | |
| public function newQueryNoEasyGlobal() | |
| { | |
| return parent::newQuery(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment