Skip to content

Instantly share code, notes, and snippets.

@vanchelo
Last active January 20, 2021 09:01
Show Gist options
  • Save vanchelo/6e903f8e322b6475af3e to your computer and use it in GitHub Desktop.
Save vanchelo/6e903f8e322b6475af3e to your computer and use it in GitHub Desktop.
Laravel Global Scopes
<?php
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use SelectableTrait;
protected $selectable = [
'id', 'title', 'created_at'
];
}
<?php
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ScopeInterface;
class SelectableScope implements ScopeInterface
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param Builder $builder
* @return void
*/
public function apply(Builder $builder)
{
$builder->select($builder->getModel()->getSelectable());
}
/**
* Remove the scope from the given Eloquent query builder.
*
* @param Builder $builder
* @return void
*/
public function remove(Builder $builder)
{
$builder->getQuery()->select(['*']);
}
}
<?php
trait SelectableTrait
{
public static function bootSelectableTrait()
{
static::addGlobalScope(new SelectableScope);
}
public function getSelectable()
{
return isset($this->selectable) ? $this->selectable : ['*'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment