如何解决这个未定义的偏移:0错误?

时间:2018-05-04 11:54:36

标签: php laravel

在会议详细信息页面中,用户为每种故障单类型选择所需数量,然后单击“下一步”并转到注册页面。在注册页面上有注册表。

会议表有一栏“all_participants”:

  • 如果all_participants为“0”,则表示仅需要收集有关正在进行注册的用户的信息,该用户是经过身份验证的用户。因此,使用auth用户的姓名和电子邮件进行注册。并且在注册表单中只需要显示与所选票证类型相关联的自定义问题(对于auth用户答案),并且应使用auth用户的id存储
  • 因此,如果all_participants为“0”并且用户在上一页中选择了票证类型 在注册中有1个或多个相关的自定义问题 出现自定义问题。如果没有与用户选择的任何故障单类型相关联的自定义问题,则用户无需插入任何信息,因为他使用其身份验证信息(姓名,姓氏和电子邮件)进行注册。

问题是当用户填写字段并点击“转到第2步”时,会显示“Undefined offset: 0”。

您知道如何正确解决此问题吗?

错误说明图:(在这种情况下,有一个自定义问题“你的手机是什么?”与用户选择的至少一种机票类型相关联)

enter image description here

//注册表

<form method="post" id="step1form" action="">
        {{csrf_field()}}
        @if (!empty($allParticipants))
            @if($allParticipants == 1)
                <p>Please fill in all fields. Your tickets will be sent to
                    p{{ (\Auth::check()) ? Auth::user()->email : old('email')}}.</p>

                @foreach($selectedTypes as $selectedType)
                    @foreach(range(1,$selectedType['quantity']) as $test)

                        <h6>Participant - 1 - {{$test}}</h6>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="" value="">
                            <label class="form-check-label d-flex align-items-center" for="exampleRadios1">
                                <span class="mr-auto">Fill the following fields with the authenticated user information.</span>
                            </label>
                        </div>
                        <div class="form-group font-size-sm">
                            <label for="participant_name" class="text-gray">Name</label>
                            <input type="text" name="participant_name[]" required class="form-control" value="">
                        </div>
                        <div class="form-group font-size-sm">
                            <label for="participant_surname" class="text-gray">Surname</label>
                            <input type="text" required class="form-control" name="participant_surname[]" value="">
                        </div>
                        <input type="hidden" name="ttypes[]" value="{{ $selectedType['id'] }}"/>
                        @foreach($selectedType['questions'] as $customQuestion)
                            <div class="form-group">
                                <label for="participant_question">{{$customQuestion->question}}</label>
                                <input type="text"
                                       @if($customQuestion->pivot->required == "1") required @endif
                                       class="form-control" name="participant_question[]">
                                <input type="hidden" name="participant_question_required[]"
                                       value="{{ $customQuestion->pivot->required }}">
                                <input type="hidden" value="{{ $customQuestion->id }}" name="participant_question_id[]"/>
                            </div>
                        @endforeach
                    @endforeach
                @endforeach
                @else
                    <p>Its not necessary aditional info. Your tickets will be sent to {{ (\Auth::check()) ? Auth::user()->email : old('email')}}.</p>

                  @if($selectedRtype['questions'] )
                      <p>You only need to answer the cutom questions below.</p>
                @foreach($selectedRtype['questions'] as $customQuestion)
                    <div class="form-group">
                        <label for="participant_question">{{$customQuestion->question}}</label>
                        <input type="text"
                               @if($customQuestion->pivot->required == "1") required @endif
                               class="form-control" name="participant_question[]">
                        <input type="hidden" name="participant_question_required[]"
                               value="{{ $customQuestion->pivot->required }}">
                        <input type="hidden" value="{{ $customQuestion->id }}" name="participant_question_id[]"/>
                    </div>
                @endforeach
        @endif

                @endif
            @endif

        <input type="submit" href="#step2"
               id="goToStep2Free" class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
    </form>

//单击“转到步骤2”按钮时调用的RegistrationController的storeUSerInfo方法:

public function StoreUserInfo(Request $request, $id, $slug = null, Validator $validator){
    $allParticipants = Congress::where('id', $id)->first()->all_participants;
    $user = Auth::user();

    if($allParticipants){
        $rules = [
            'participant_name.*' => 'required|max:255|string',
            'participant_surname.*' => 'required|max:255|string',
        ];

        $messages = [
            'participant_question.*.required' => 'The participant is required'
        ];

        foreach ($request->participant_question_required as $key => $value) {
            $rule = 'string|max:255'; // I think string should come before max
            //dd($value);
            // if this was required, ie 1, prepend "required|" to the rule
            if ($value) {
                $rule = 'required|' . $rule;
            }

            // add the individual rule for this array key to the $rules array
            $rules["participant_question.{$key}"] = $rule;
        }

        $validator = Validator::make($request->all(), $rules, $messages);

        if($validator->passes()) {
            $registration = Registration::create([
                'congress_id' => $id,
                'main_participant_id' => $user->id,
                'status' => 'C',
            ]);

            $participants = [];

            for ($i = 0; $i < count($request->participant_name); $i++)
                $participants[] = Participant::create([
                    'name' => $request->participant_name[$i],
                    'surname' => $request->participant_surname[$i],
                    'registration_id' => $registration->id,
                    'ticket_type_id' => $request->rtypes[$i]

                ]);

            for ($i = 0; $i < count($request->participant_question); $i++)
                $answer = Answer::create([
                    'question_id' => $request->participant_question_id[$i],

                    'participant_id' => $participants[$i]->id,
                    'answer' => $request->participant_question[$i],
                ]);
            }

        return response()->json([
            'success' => true,
            'message' => 'success'
        ], 200);
    }


    else {

        $messages = [
            'participant_question.*.required' => 'The participant is required'
        ];


        foreach ($request->participant_question_required as $key => $value) {
            $rule = 'string|max:255'; // I think string should come before max
            //dd($value);
            // if this was required, ie 1, prepend "required|" to the rule
            if ($value) {
                $rule = 'required|' . $rule;
            }

            // add the individual rule for this array key to the $rules array
            $rules["participant_question.{$key}"] = $rule;
        }


        $validator = Validator::make($request->all(), $rules, $messages);


        if ($validator->passes()) {

            $registration = Registration::create([
                'congress_id' => $id,
                'main_participant_id' => $user->id,
                'status' => 'C',

            ]);

            $participants = [];

            for ($i = 0; $i < count($request->participant_name); $i++)
                $participants[] = Participant::create([
                    'name' => '',
                    'surname' => '',
                    'registration_id' => $registration->id,
                    'ticket_type_id' => $request->rtypes[$i]

                ]);

            for ($i = 0; $i < count($request->participant_question); $i++)
                $answer = Answer::create([
                    'question_id' => $request->participant_question_id[$i],
                        // the error undefined offset is here
                    'participant_id' => $participants[$i]->id,
                    'answer' => $request->participant_question[$i],
                ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'success'
        ], 200);

    }
}

与问题相关的Db结构:

congresses: id, name, all_participants,...
ticekt type table: id, name, etc
registrations: id, congress_id (fk), main_participant_id (main_participant_id is the id of the auth user the user that does the registration)
participants: id registration_id (fk), ticket_type_id (fk), name, surname
questions: id, question, congress_id (fk)
ticket_type_questions pivot table: id, ticket_type_id, question_id, required (required is 1 or 0, 1 means required)

1 个答案:

答案 0 :(得分:0)

只需搜索0:访问数组的密钥时,您必须确保密钥存在。

我看到4个带有$i = 0;声明的for循环用于访问数组但从未检查过。另外,您可能只想使用foreach循环,但这取决于您。

检查密钥是否存在

if (isset($request->participant_question_id[$i])) {
    $answer = Answer::create([
        'question_id' => $request->participant_question_id[$i],
        // the error undefined offset is here
        'participant_id' => $participants[$i]->id,
        'answer' => $request->participant_question[$i],
    ]);
}

foreach方法

foreach ($request->participant_question as $key => $question)
    $answer = Answer::create([
        'question_id' => $question,
        // the error undefined offset is here
        'participant_id' => $participants[$i]->id,
        'answer' => $request->participant_question[$i],
    ]);
}