Laravel 4 Global Scope (fields for select)
<?php
trait SelectableTrait
{
public static function bootSelectableTrait()
{
static::addGlobalScope(new SelectableScope);
}
public function getSelectableColumns()
{
return isset($this->selectable) ? $this->selectable : ['*'];
}
}<?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
use Illuminate\Database\Eloquent\Model;
class ModelWithScope extends Model
{
use SelectableTrait;
protected $selectable = [
'id', 'title', 'created_at'
];
}