Как отобразить несколько foreach? - PullRequest
1 голос
/ 25 мая 2019

Я изменил модель экзаменов, чтобы сохранить ExamQuestions из hasMany в ownTo, и вот как я изменил свой контроллер.Я получаю неверный аргумент для foreach () в представлении.

Вот модель Экзамен , которую я изменил

     public function questions()
  {
      return $this->belongsTo(ExamQuestion::class, 'exam_questions');
  }

Вот мой контроллер

public function exam($course_id, Request $request)
        {
            $course = Course::where('id', $course_id)->firstOrFail();
            $answers = [];
            $exam_score = 0;
            foreach ($request->get('questions') as $question_id => $answer_id) {
                $question = ExamQuestion::find($question_id);
                $correct_answer = ExamOption::where('exam_question_id', $question_id)
                    ->where('id', $answer_id)
                    ->where('is_correct', 1)->count() > 0;
                $answers[] = [

                    'exam_question_id' => $question_id,
                    'exam_option_id' => $answer_id,
                    'corect' => $correct_answer
                ];
                if ($correct_answer) {
                    $exam_score += $question->score;
                }
            }

            $exam_result = ExamResult::create([
              'exam_id' => $course->exam->id,
              'employee_id' => \Auth::id(),
              'result' => $exam_score,
            ]);
            $exam_result->answers()->createMany($answers);

            $get_reslts_score= Exam::with('exam_results')->first();
            $x = $get_reslts_score->passing_grade;

            if($exam_result->result >= $x) {
              $exam_result->is_complete = 1;
              $exam_result->save();
}

            return redirect()->route('learn.show', [$course, $request])->with('message', 'Test score: ' . $exam_score);
        }

Вот мой взгляд

  <h3>@if ($courses->exam)</h3>
  <hr/>
    <div class="row">
      <div class="col-xs-12 form-group">

      <form action="{{ route('exam.save', [$courses->id]) }}" method="post">
      {{ csrf_field() }}


        @foreach($courses->exam->questions as $question)

        <br>{{$loop->iteration}} . {{$question->question}}</b>
        </br>

        @foreach($questions->exam_options as $option)
        &nbsp;<input type="radio" name="question[{{ $question->id }}]" value="{{ $option->id }}"/>&nbsp;&nbsp;{{ $option->text }}</br>
        @endforeach


        <br>
        @endforeach

1 Ответ

1 голос
/ 25 мая 2019
  <h3>@if ($courses->exam)</h3>
  <hr/>
  <div class="row">
      <div class="col-xs-12 form-group">
         <form action="{{ route('exam.save', [$courses->id]) }}" method="post">
              {{ csrf_field() }}
           @foreach($courses->exam->questions as $questions)
               <br>{{$loop->iteration}} . {{$questions->question}}</b>
               </br>

            @foreach($questions->exam_options as $option)
               &nbsp;<input type="radio" name="question[{{ $questions->id }}]" value="{{ $option->id }}"/>&nbsp;&nbsp;{{ $option->text }}</br>
            @endforeach
            <br>
          @endforeach

Если это не сработало, пожалуйста, проверьте возвращаемые значения отношений модели или нет. Используя parent для рекурсивного просмотра полного массива, вы можете перейти на любой уровень глубины здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...