app/Http/Controllers/QuestionsController.php
/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
Store a newly created resource in storage.
Store a newly created resource in storage .
public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'question' => ['required', 'string'],
            'answers' => ['required'],
        ]);
        if ($validator->fails()) {
                    return response()->json(['error'=>$validator->errors()], 401);
                }
        $question = new Questions();
        $question->question = $request->question;
        $question->status = $request->status;
        $question->save();
        foreach($request->answers as $ans){
            $answer = new Answers();
            $answer->question_id = $question->id;
            $answer->answer = $ans;
            $answer->save();
        }
        $data['question_id'] = $question->id;
        $data['question'] = $question->question;
        $all_answer = [];
        foreach ($question->answers as $one) {
            $all_answer[] = [
                'answer_id'=>$one->id,
                'answer'=>$one->answer,
            ];
        }
        $data['answers'] = $all_answer;
        return response()->json([ $data], $this-> successStatus);
    }
public function store ( Request $ request ) { $ validator = Validator :: make ( $ request -> all ( ) , [ 'question' => [ 'required' , 'string' ] , 'answers' => [ 'required' ] , ] ) ; if ( $ validator -> fails ( ) ) { return response ( ) -> json ( [ 'error' => $ validator -> errors ( ) ] , 401 ) ; } $ question = new Questions ( ) ; $ question -> question = $ request -> question ; $ question -> status = $ request -> status ; $ question -> save ( ) ; foreach ( $ request -> answers as $ ans ) { $ answer = new Answers ( ) ; $ answer -> question_id = $ question -> id ; $ answer -> answer = $ ans ; $ answer -> save ( ) ; } $ data [ 'question_id' ] = $ question -> id ; $ data [ 'question' ] = $ question -> question ; $ all_answer = [ ] ; foreach ( $ question -> answers as $ one ) { $ all_answer [ ] = [ 'answer_id' => $ one -> id , 'answer' => $ one -> answer , ] ; } $ data [ 'answers' ] = $ all_answer ; return response ( ) -> json ( [ $ data ] , $ this -> successStatus ) ; }
Store a newly created resource in storage.
Store a newly created resource in storage .
// 'answer2' => ['required', 'string', 'max:255'], // 'answer3' => ['required', 'string', 'max:255'], // dd($question->answers);