FAQS store api with array

PHOTO EMBED

Fri May 03 2024 10:55:45 GMT+0000 (Coordinated Universal Time)

Saved by @zeinrahmad99

  /**
     * @OA\Post(
     * path="/admin/faqs",
     * description="Add new faq.",
     * tags={"Admin - FAQs"},
     * security={{"bearer_token": {} }},
     *   @OA\RequestBody(
     *       required=true,
     *       @OA\MediaType(
     *           mediaType="application/json",
     *           @OA\Schema(
     *              required={"question", "answer"},
     *                 @OA\Property(
     *                     property="question",
     *                     type="array",
     *                     @OA\Items(type="string"),
     *                     description="Array of question strings"
     *                 ),
     *                 @OA\Property(
     *                     property="answer",
     *                     type="array",
     *                     @OA\Items(type="string"),
     *                     description="Array of answer strings"
     *                 ),
     * 
     *          )
     *       )
     *   ),
     * @OA\Response(
     *    response=200,
     *    description="successful operation",
     *     ),
     *   @OA\Response(
     *     response=401,
     *     description="Unauthenticated",
     *  ),
     *   @OA\Response(
     *     response=422,
     *     description="The question field must be an array. | The answer field must be an array. | The question field is required. | The answer field is required.",
     *  )
     * )
     * )
     */

    // TODO ask MJ if he want arrays or just one pair question and answer
    public function store(Request $request)
    {
        $request->validate([
            'question' => ['required', 'array'],
            'question.*' => ['required', 'string'],
            'answer' => ['required', 'array'],
            'answer.*' => ['required', 'string'],
        ]);

        $questions = $request->input('question');
        $answers = $request->input('answer');

        $faqs = [];
        $count = min(count($questions), count($answers));
        for ($i = 0; $i < $count; $i++) {
            $faq = Faq::create([
                'question' => $questions[$i],
                'answer' => $answers[$i],
            ]);
            $faqs[] = new FAQResource($faq);
        }

        return response()->json(FAQResource::collection($faqs), 200);
    }
content_copyCOPY