QuestionSearchController.php 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Question;
  5. use Illuminate\Http\JsonResponse;
  6. use Illuminate\Http\Request;
  7. class QuestionSearchController extends Controller
  8. {
  9. public function __invoke(Request $request): JsonResponse
  10. {
  11. $query = Question::query();
  12. if ($search = $request->string('q')->toString()) {
  13. $query->search($search);
  14. }
  15. if ($kpCode = $request->string('kp_code')->toString()) {
  16. $query->where('kp_code', $kpCode);
  17. }
  18. if ($type = $request->string('question_type')->toString()) {
  19. $query->where('question_type', $type);
  20. }
  21. $min = $request->float('difficulty_min');
  22. $max = $request->float('difficulty_max');
  23. if ($min !== null && $max !== null) {
  24. $query->whereBetween('difficulty', [$min, $max]);
  25. }
  26. $perPage = max(1, min(50, (int) $request->input('per_page', 20)));
  27. return response()->json($query->paginate($perPage));
  28. }
  29. }