33namespace Ivy \Shared \Infrastructure \Service ;
44
55use Illuminate \Database \Eloquent \Builder ;
6+ use Ivy \Shared \Traits \ResolvesRequestInput ;
7+ use Symfony \Component \HttpFoundation \Request ;
68
79class SearchService
810{
11+ use ResolvesRequestInput;
12+
913 public function apply (
1014 Builder $ query ,
11- string $ term ,
12- array $ columns
15+ Request $ request ,
16+ array $ columns = []
1317 ): Builder {
1418
19+ $ term = $ this ->string ($ request , 'search ' );
20+
1521 if ($ term === '' || empty ($ columns )) {
1622 return $ query ;
1723 }
1824
1925 $ model = $ query ->getModel ();
20- $ baseTable = $ model ->getTable ();
21-
22- $ query ->where (function (Builder $ q ) use ($ baseTable , $ term , $ columns ) {
26+ $ table = $ model ->getTable ();
2327
24- $ isFirst = true ;
28+ $ query -> where ( function ( Builder $ q ) use ( $ table , $ term , $ columns ) {
2529
2630 foreach ($ columns as $ column ) {
2731
2832 if (!str_contains ($ column , '. ' )) {
33+ $ q ->orWhere (
34+ "{$ table }. {$ column }" ,
35+ 'LIKE ' ,
36+ "% {$ term }% "
37+ );
2938
30- if ($ isFirst ) {
31- $ q ->where (
32- "$ baseTable. $ column " ,
33- 'LIKE ' ,
34- "% {$ term }% "
35- );
36- } else {
37- $ q ->orWhere (
38- "$ baseTable. $ column " ,
39- 'LIKE ' ,
40- "% {$ term }% "
41- );
42- }
43-
44- $ isFirst = false ;
4539 continue ;
4640 }
4741
48- $ this ->applyRelationSearch ($ q , $ column , $ term , $ isFirst );
49-
50- $ isFirst = false ;
42+ $ this ->applyRelationSearch ($ q , $ column , $ term );
5143 }
5244 });
5345
@@ -57,17 +49,14 @@ public function apply(
5749 protected function applyRelationSearch (
5850 Builder $ query ,
5951 string $ path ,
60- string $ term ,
61- bool $ useWhereInsteadOfOr = false
52+ string $ term
6253 ): void {
6354
6455 $ segments = explode ('. ' , $ path );
6556 $ field = array_pop ($ segments );
66- $ relationPath = implode ('. ' , $ segments );
67-
68- $ method = $ useWhereInsteadOfOr ? 'whereHas ' : 'orWhereHas ' ;
57+ $ relation = implode ('. ' , $ segments );
6958
70- $ query ->{ $ method }( $ relationPath , function (Builder $ q ) use ($ field , $ term ) {
59+ $ query ->orWhereHas ( $ relation , function (Builder $ q ) use ($ field , $ term ) {
7160 $ q ->where ($ field , 'LIKE ' , "% {$ term }% " );
7261 });
7362 }
0 commit comments