6
6
use Domains \Discussions \Models \Question ;
7
7
use Domains \Discussions \Resources \QuestionResource ;
8
8
use Illuminate \Contracts \Auth \Factory as Auth ;
9
+ use Illuminate \Database \Eloquent \Builder ;
9
10
use Illuminate \Http \Request ;
10
11
use Illuminate \Http \Resources \Json \AnonymousResourceCollection ;
11
12
12
13
class QuestionsGetController extends Controller
13
14
{
14
- protected $ query ;
15
+ protected Question $ question ;
15
16
16
17
public function __construct (Auth $ auth , Question $ question )
17
18
{
18
19
if ($ auth ->guard ()->guest ()) {
19
20
$ this ->middleware ('throttle:30,1 ' );
20
21
}
21
22
22
- $ this ->query = $ question:: query () ;
23
+ $ this ->question = $ question ;
23
24
}
24
25
25
26
public function __invoke (Request $ request ): AnonymousResourceCollection
@@ -33,28 +34,19 @@ public function __invoke(Request $request): AnonymousResourceCollection
33
34
'resolved ' => 'sometimes|boolean '
34
35
]);
35
36
36
- $ author = $ request ->get ('author ' );
37
- if ($ author != '' ) {
38
- $ this ->query ->where ('author_id ' , $ author );
39
- }
40
-
41
- $ title = strtoupper ($ request ->get ('title ' ));
42
- if ($ title != '' ) {
43
- $ this ->query ->where ('title ' , 'like ' , '% ' .$ title .'% ' );
44
- }
45
-
46
- $ created = $ request ->get ('created ' );
47
- if ($ created != null ) {
48
- $ this ->query ->whereBetween ('created_at ' , [$ created ['from ' ], $ created ['to ' ]]);
49
- }
50
-
51
- $ resolved = $ request ->get ('resolved ' );
52
- if ($ resolved == true ) {
53
- $ this ->query ->whereNotNull ('resolved_at ' );
54
- } elseif ($ resolved == false ) {
55
- $ this ->query ->whereNull ('resolved_at ' );
56
- }
57
-
58
- return QuestionResource::collection ($ this ->query ->paginate (15 ));
37
+ $ question = $ this ->question
38
+ ->when ($ authorId = $ request ->get ('author ' ),
39
+ fn (Builder $ query , int $ authorId ) => $ query ->where ('author_id ' , $ authorId ))
40
+ ->when ($ request ->get ('title ' ),
41
+ fn (Builder $ query , string $ title ) => $ query ->where ('title ' , 'like ' , '% ' .strtoupper ($ title ).'% ' ))
42
+ ->when ($ request ->get ('created ' ),
43
+ fn (Builder $ query , array $ created ) => $ query ->whereBetween ('created_at ' , [$ created ['from ' ], $ created ['to ' ]]))
44
+ ->when ($ request ->get ('resolved ' ),
45
+ fn (Builder $ query , bool $ resolved ) => $ query ->whereNotNull ('resolved_at ' ))
46
+ ->when (!$ request ->get ('resolved ' ),
47
+ fn (Builder $ query , bool $ resolved ) => $ query ->whereNull ('resolved_at ' ))
48
+ ->simplePaginate (15 );
49
+
50
+ return QuestionResource::collection ($ question );
59
51
}
60
52
}
0 commit comments