diff --git a/CHANGELOG.md b/CHANGELOG.md index 24591f5..33cb1ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +## 3.1.0 + +`Laraquick\Models\Traits\Helper` now has an `except` scope method to remove provided +columns from selection. Thanks @mykeels. + ## 3.0.5 Response method `paginatedList()` now takes a third parameter, an array diff --git a/src/Models/Traits/Helper.php b/src/Models/Traits/Helper.php index d794dfc..5b156b9 100644 --- a/src/Models/Traits/Helper.php +++ b/src/Models/Traits/Helper.php @@ -4,7 +4,8 @@ use Illuminate\Database\Eloquent\Builder; -trait Helper { +trait Helper +{ /** * A shortcut to withoutGlobalScope() @@ -16,19 +17,39 @@ public function without($attributes) { return $this->withoutGlobalScope($attributes); } - + + /** + * Excludes the given values from being selected from the database + * Thanks to Ikechi Michael (@mykeels) + * + * @param Builder $query + * @param string|array $value + * @return void + */ + public function scopeExcept($query, $value) + { + $defaultColumns = ['id', 'created_at', 'updated_at']; + if (in_array_('deleted_at', $this->dates)) { + $defaultColumns[] = 'deleted_at'; + } + if (is_string($value)) { + $value = [$value]; + } + return $query->select(array_diff(array_merge($defaultColumns, $this->fillable), (array) $value)); + } + public function toArray() { $fillable = $this->fillable; $fillable[] = 'id'; - // Show only fillables + // Show only fillables $array = collect(parent::toArray()) ->only($fillable) ->all(); - // Add loaded relations - foreach (array_keys($this->relations) as $relation) { - $array[$relation] = $this->$relation; - } - return $array; + // Add loaded relations + foreach (array_keys($this->relations) as $relation) { + $array[$relation] = $this->$relation; + } + return $array; } -} \ No newline at end of file +}