Last active
January 20, 2021 09:01
-
-
Save vanchelo/6e903f8e322b6475af3e to your computer and use it in GitHub Desktop.
Laravel Global Scopes
This file contains 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 Post extends Model | |
{ | |
use SelectableTrait; | |
protected $selectable = [ | |
'id', 'title', 'created_at' | |
]; | |
} |
This file contains 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()->getSelectable()); | |
} | |
/** | |
* 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 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 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