Skip to content

Instantly share code, notes, and snippets.

@sgelbart
Last active September 22, 2016 09:55
Show Gist options
  • Save sgelbart/781f6d483601d2a5efd8 to your computer and use it in GitHub Desktop.
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)
<?php
//USAGE
//in your model
public function scopeGlobal($query)
{
//todo: there may be a bug where you can't use nested wheres..try with ->where(function($query){return MyModel::noEasyGlobal();}
return MyModel::noEasyGlobal()->where('is_published',1); //replace this with whatever criteria you ahve
}
//in your controllers
MyModel::all(); //has global
MyModel::noEasyGlobal(); //no global
?>
<?php
/**
* 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 LaravelEasyGlobalScope {
/**
* @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();
}
/**
* Get a new query builder that doesn't have any global scopes.
* By default Model's method calls newQuery and we end up with recursion if we don't change to newQueryNoEasyGlobal
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function newQueryWithoutScopes()
{
return $this->removeGlobalScopes($this->newQueryNoEasyGlobal());
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment