Skip to content

Instantly share code, notes, and snippets.

@oliverlundquist
Created September 25, 2015 03:17
Show Gist options
  • Save oliverlundquist/bd1a26d091c17796b557 to your computer and use it in GitHub Desktop.
Save oliverlundquist/bd1a26d091c17796b557 to your computer and use it in GitHub Desktop.
Active Global Scope Query Laravel
<?php namespace App;
use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class ActiveScope implements ScopeInterface
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->where('active', '=', 1);
}
/**
* Remove the scope from the given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function remove(Builder $builder, Model $model)
{
$query = $builder->getQuery();
$bindings = $query->getRawBindings()['where'];
$bindingKey = 0;
foreach ((array)$query->wheres as $key => $where) {
if ($where['type'] === 'Basic' && $where['column'] === 'active' && $where['value'] === 1) {
unset($query->wheres[$key]); //remove wheres
unset($bindings[$bindingKey]); //remove where bindings
}
if ( ! in_array($where['type'], ['Null', 'NotNull'])) {
$bindingKey++;
}
}
$query->wheres = array_values($query->wheres); //reset wheres
$query->setBindings($bindings); //reset where bindings
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment