Skip to content

Instantly share code, notes, and snippets.

@thehelvetian
Forked from luckys383/FilterTrait.php
Created June 14, 2019 01:17
Show Gist options
  • Save thehelvetian/c91671829bb5cddf2fe575a9f95db584 to your computer and use it in GitHub Desktop.
Save thehelvetian/c91671829bb5cddf2fe575a9f95db584 to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits;
trait FilterTrait {
/**
* add filtering.
*
* @param $builder: query builder.
* @param $filters: array of filters.
* @return query builder.
*/
public function scopeFilter($builder, $filters = [])
{
if(!$filters) {
return $builder;
}
$tableName = $this->getTable();
$defaultFillableFields = $this->fillable;
foreach ($filters as $field => $value) {
if(in_array($field, $this->boolFilterFields) && $value != null) {
$builder->where($field, (bool)$value);
continue;
}
if(!in_array($field, $defaultFillableFields) || !$value) {
continue;
}
if(in_array($field, $this->likeFilterFields)) {
$builder->where($tableName.'.'.$field, 'LIKE', "%$value%");
} else if(is_array($value)) {
$builder->whereIn($field, $value);
} else {
$builder->where($field, $value);
}
}
return $builder;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment