-
-
Save Ellrion/64f8abb5901dc028b22b to your computer and use it in GitHub Desktop.
Laravel 4 Global Scope (fields for select)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Database\Eloquent\Model; | |
class ModelWithScope extends Model | |
{ | |
use SelectableTrait; | |
protected $selectable = [ | |
'id', 'title', 'created_at' | |
]; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(['*']); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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