Skip to content

Commit

Permalink
Added 'except' to model Helper trait
Browse files Browse the repository at this point in the history
  • Loading branch information
ezra-obiwale committed Jan 25, 2018
1 parent 0c3d568 commit 3df4e68
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
39 changes: 30 additions & 9 deletions src/Models/Traits/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

use Illuminate\Database\Eloquent\Builder;

trait Helper {
trait Helper
{

/**
* A shortcut to withoutGlobalScope()
Expand All @@ -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;
}
}
}

0 comments on commit 3df4e68

Please sign in to comment.