Skip to content

Instantly share code, notes, and snippets.

@sgelbart
Last active September 22, 2016 09:55
Show Gist options
  • Select an option

  • Save sgelbart/781f6d483601d2a5efd8 to your computer and use it in GitHub Desktop.

Select an option

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's currently a bug where where you can't use nested wheres!!
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 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