-
-
Save thehelvetian/c91671829bb5cddf2fe575a9f95db584 to your computer and use it in GitHub Desktop.
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 | |
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