-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFilterable.php
More file actions
90 lines (79 loc) · 2.23 KB
/
Filterable.php
File metadata and controls
90 lines (79 loc) · 2.23 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace App;
trait Filterable{
public function scopeFilter($query,$request){
if(!$request) return $query;
foreach($request as $operation => $arguments){
/**
* actually whereHas. We loop through each value and organize it
* in a way so that we can pass to scopeFilter in the related model
*/
if($operation == 'has') {
$queries = [];
foreach($arguments as $key => $val){
list($related,$field) = explode('.',$key);
if(!isset($queries[$related])) $queries[$related] = [];
$queries[$related][$field] = $val;
}
foreach($queries as $relation => $fields){
$query->whereHas($relation,function($query) use($fields){
$query->Filter($fields);
});
}
continue;
}
/**
* with() operation. Converts $val to array if it isn't.
* replaces ":" to "." to allow ("model.otherModel")
*/
if($operation == 'with'){
if(!is_array($arguments)) $arguments = [$arguments];
$query->with(...array_map(function($a){
return str_replace(':','.',$a);
},$arguments));
continue;
}
/**
* Dead simple here on...
*/
if($operation == 'limit'){
$query->limit($arguments);
continue;
}
if($operation == 'offset'){
$query->offset($arguments);
continue;
}
if($operation == 'orderBy'){
$query->orderBy(explode(',',$arguments));
continue;
}
if($operation == 'fields'){
$query->select(explode(',',$arguments));
continue;
}
/**
* where()
* we search for the "_$operations" suffix in the key names
* if not there, query and bail out
*/
$operations = ['eq','gt','lt','bt','like'];
$parts = explode('_',$operation);
if(!in_array(end($parts),$operations)){
if(!is_array($arguments)) $arguments = [$arguments];
$query->where($operation,...$arguments);
continue;
}
/**
* We found the operation. Just query and walk away
*/
$op = array_splice($parts,-1,1)[0];
$column = implode('_',$parts);
$op == 'gt' and $query->where($column,'>',$arguments);
$op == 'lt' and $query->where($column,'<',$arguments);
$op == 'like' and $query->where($column,'like',$arguments);
$op == 'bt' and $query->whereBetween($column,explode(',',$arguments));
}
return $query;
}
}