forked from n7olkachev/laravel-filterable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFilterable.php
36 lines (28 loc) · 954 Bytes
/
Filterable.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
namespace N7olkachev\LaravelFilterable;
use N7olkachev\LaravelFilterable\Exceptions\FilterableException;
trait Filterable
{
public function scopeFilter($query, array $filterData = [])
{
foreach ($filterData as $key => $value) {
if (!$this->isFilterable($key)) {
throw new FilterableException("[$key] is not allowed for filtering");
}
if (is_null($value) || $value === '') continue;
$scopeName = ucfirst(camel_case($key));
if (method_exists($this, 'scope' . $scopeName)) {
$query->$scopeName($value);
} else if (is_array($value)) {
$query->whereIn($key, $value);
} else {
$query->where($key, $value);
}
}
}
protected function isFilterable($key)
{
$filterable = $this->filterable ?: [];
return in_array($key, $filterable);
}
}