Last active
June 4, 2019 11:26
-
-
Save luckys383/0bd97434122749ab21ec6d2ab7a53339 to your computer and use it in GitHub Desktop.
Laravel: Common Filters using Model Scope
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\Models; | |
| use Illuminate\Database\Eloquent\Model; | |
| class AppModel extends Model | |
| { | |
| /** | |
| * set fillable fields | |
| */ | |
| protected $fillable = []; | |
| /** | |
| * set string fields for filtering | |
| * @var array | |
| */ | |
| protected $likeFilterFields = []; | |
| /** | |
| * set boolean fields for filtering | |
| * @var array | |
| */ | |
| protected $boolFilterFields = ['status']; | |
| /** | |
| * 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