Skip to content

Instantly share code, notes, and snippets.

@Ellrion
Forked from vanchelo/Post.php
Last active August 29, 2015 14:06
Show Gist options
  • Save Ellrion/64f8abb5901dc028b22b to your computer and use it in GitHub Desktop.
Save Ellrion/64f8abb5901dc028b22b to your computer and use it in GitHub Desktop.
Laravel 4 Global Scope (fields for select)
<?php
use Illuminate\Database\Eloquent\Model;
class ModelWithScope 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()->getSelectableColumns());
}
/**
* 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 getSelectableColumns()
{
return isset($this->selectable) ? $this->selectable : ['*'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment