QuestionRandomController.php 852 B

123456789101112131415161718192021222324252627282930313233
  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 QuestionRandomController extends Controller
  8. {
  9. public function __invoke(Request $request): JsonResponse
  10. {
  11. $limit = max(1, min(50, (int) $request->input('limit', 10)));
  12. $query = Question::query();
  13. if ($kpCode = $request->string('kp_code')->toString()) {
  14. $query->where('kp_code', $kpCode);
  15. }
  16. if ($type = $request->string('question_type')->toString()) {
  17. $query->where('question_type', $type);
  18. }
  19. $questions = $query->inRandomOrder()->limit($limit)->get();
  20. return response()->json([
  21. 'count' => $questions->count(),
  22. 'data' => $questions,
  23. ]);
  24. }
  25. }