33namespace Ivy \Shared \Traits ;
44
55use Illuminate \Database \Eloquent \Builder ;
6+ use Ivy \Shared \Infrastructure \Service \SortService ;
67use Symfony \Component \HttpFoundation \Request ;
8+ use Illuminate \Container \Container ;
79
810trait HasSorting
911{
@@ -13,29 +15,24 @@ public function scopeSort(
1315 string $ defaultColumn = 'id ' ,
1416 string $ defaultDirection = 'asc '
1517 ): Builder {
16- $ columns = static ::$ sortable ?? ['id ' ];
1718
18- if (!in_array ($ defaultColumn , $ columns , true ) && $ defaultColumn !== 'id ' ) {
19- throw new \InvalidArgumentException (
20- "Invalid default sort column [ $ defaultColumn] "
21- );
22- }
19+ $ columns = static ::$ sortable ?? ['id ' ];
2320
2421 $ column = $ request ->query ->get ('sort ' , $ defaultColumn );
2522 $ direction = strtolower (
2623 $ request ->query ->get ('direction ' , $ defaultDirection )
2724 );
2825
29- if (!in_array ($ column , $ columns , true )) {
30- $ column = $ defaultColumn ;
31- }
32-
3326 if (!in_array ($ direction , ['asc ' , 'desc ' ], true )) {
3427 $ direction = $ defaultDirection ;
3528 }
3629
37- return $ query
38- ->reorder ()
39- ->orderBy ($ column , $ direction );
30+ return Container::getInstance ()->get (SortService::class)->apply (
31+ $ query ,
32+ $ column ,
33+ $ columns ,
34+ $ defaultColumn ,
35+ $ direction
36+ );
4037 }
4138}
0 commit comments