Получение "Неопределенное смещение: 2 ошибки (ошибка в: 'member_id' => $ members [$ i] -> id,) - PullRequest
0 голосов
/ 03 июня 2018

У меня есть код ниже, чтобы пользователь мог ввести некоторые данные для регистрации на конференции.Тогда у меня есть магазин RegistrationController RegistratioInfo ().Когда пользователь заполняет форму и отправляет форму, делается ajax-запрос и появляется ошибка:

{message: «Неопределенное смещение: 2», исключение: «ErrorException»,…} исключение:Файл «ErrorException»: RegistrationController.php »строка: 194 сообщение:« Неопределенное смещение: 2 »трассировка: [,…]

Строка 194 такая:

'participant_id' => $participants[$i]->id,

Полный метод storeRegistration () приведен ниже.

Код в представлении:

@foreach($selectedRtypes as $k => $selectedRtype)
    @foreach(range(1,$selectedRtype['quantity']) as $val)

        @if($allParticipants == 1)
            <h6 class="text-heading-blue mb-3 pb-2 font-weight-bold">
                Participant - {{$val}} - {{$k}}</h6>

            <div class="form-group font-size-sm">
                <label for="name{{ $k }}_{{ $val }}"
                       class="text-gray">Name</label>
                <input type="text" id="name{{ $k }}_{{ $val }}"
                       name="participant_name[]" required
                       class="form-control" value="">
            </div>
            <div class="form-group font-size-sm">
                <label for="surname{{ $k }}_{{ $val }}"
                       class="text-gray">Surname</label>
                <input type="text" id="surname{{ $k }}_{{ $val }}"
                       required class="form-control"
                       name="participant_surname[]" value="">
            </div>
            @foreach($selectedRtype['questions'] as $customQuestion)
                <div class="form-group">
                    <label for="participant_question">{{$customQuestion->question}}</label>
                    @if($customQuestion->hasOptions())
                        {!! $customQuestion->getHtmlInput(
                            $customQuestion->name,
                            $customQuestion->options,
                            ($customQuestion->pivot->required == '1'),
                            'form-control',
                            $customQuestion->type)
                        !!}
                    @endif
                    <input type="hidden"
                           name="participant_question_required[]"
                           value="{{ $customQuestion->pivot->required }}">
                    <input type="hidden"
                           value="{{ $customQuestion->id }}"
                           name="participant_question_id[]"/>
                </div>
            @endforeach
        @else
            <input type="hidden" value="foo"
                   name="participant_name[]"/>
            <input type="hidden" value="bar"
                   name="participant_surname[]"/>
        @endif
        <input type="hidden" name="rtypes[]"
               value="{{ $selectedRtype['id'] }}"/>
    @endforeach
    @if ($allParticipants == 0)
        @foreach($selectedRtype['questions'] as $customQuestion)

            <div class="form-group">
                <label for="participant_question">{{$customQuestion->question}}</label>
                @if($customQuestion->hasOptions())
                    {!! $customQuestion->getHtmlInput(
                        $customQuestion->name,
                        $customQuestion->options,
                        ($customQuestion->pivot->required == '1'),
                        'form-control',
                        $customQuestion->type)
                    !!}
                @endif
                <input type="hidden"
                       name="participant_question_required[]"
                       value="{{ $customQuestion->pivot->required }}">
                <input type="hidden"
                       value="{{ $customQuestion->id }}"
                       name="participant_question_id[]"/>
            </div>
        @endforeach
    @endif
@endforeach

storeRegistration ():

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

        $rules = [];
        $messages = [];

        if (isset($request->participant_question_required)) {
            $messages = [
                'participant_question.*.required' => 'Fill all mandatory fields.',
                'participant_name.*.required' => 'Fill the field name.',
                'participant_surname.*.required' => 'Fill the field surname.',
            ];

            foreach ($request->participant_question_required as $key => $value) {
                $rule = 'string|max:255'; // I think string should come before max
                // 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;
            }
        }

        if ($allParticipants) {

            $rules["participant_name.*"] = 'required|max:255|string';
            $rules["participant_surname.*"] = 'required|max:255|string';

        }

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

        $errors = $validator->errors();
        $errors = json_decode($errors);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $errors
            ], 422);
        }

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

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

                ]);
            }
            if (isset($request->participant_question))
                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);
    }

Если есть пользовательский вопрос, дляНапример, «Получать уведомления» сгенерированный html имеет вид:

<div class="form-group">
    <label for="participant_question">Receive Notifications?</label>                                      
    <div class="form-check">
        <input type="checkbox" name="participant_question[]" value="Yes" class="form-check-input" 1=""> 
        <label class="form-check-label" for="exampleCheck1">Yes</label></div> 
    <div class="form-check">
        <input type="checkbox" name="participant_question[]" value="No" class="form-check-input" 1="">    
        <label class="form-check-label" for="exampleCheck1">No</label></div>
        <input type="hidden" name="participant_question_required[]" value="1">
        <input type="hidden" value="2" name="participant_question_id[]">
</div>

«dd ($ request-> member_question)» в storeRegistration () показывает, если для первого участника выбрано «Да», а дляВторой участник "нет" показывает:

array:2 [
  0 => "Yes"
  1 => "No"
]

dd($participant) в:

if (isset($request->participant_question)) {
          for ($i = 0; $i < count($request->participant_question); $i++) {
               dd($participants);
               ...

Показывает:

array:2 [
  0 => Participant {#287
    #fillable: array:4 [
      0 => "name"
      1 => "surname"
      2 => "registration_id"
      3 => "registration_type_id"
    ]
    #connection: "mysql"
    #table: null
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: true
    #attributes: array:7 [
      "name" => "John"
      "surname" => "Keane"
      "registration_id" => 24
      "registration_type_id" => "1"
      "updated_at" => "2018-06-03 13:07:18"
      "created_at" => "2018-06-03 13:07:18"
      "id" => 47
    ]
    #original: array:7 [
      "name" => "John"
      "surname" => "Keane"
      "registration_id" => 24
      "registration_type_id" => "1"
      "updated_at" => "2018-06-03 13:07:18"
      "created_at" => "2018-06-03 13:07:18"
      "id" => 47
    ]
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #guarded: array:1 [
      0 => "*"
    ]
  }
  1 => Participant {#289
    #fillable: array:4 [
      0 => "name"
      1 => "surname"
      2 => "registration_id"
      3 => "registration_type_id"
    ]
    #connection: "mysql"
    #table: null
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: true
    #attributes: array:7 [
      "name" => "Jake"
      "surname" => "L"
      "registration_id" => 24
      "registration_type_id" => "1"
      "updated_at" => "2018-06-03 13:07:18"
      "created_at" => "2018-06-03 13:07:18"
      "id" => 48
    ]
    #original: array:7 [
      "name" => "Jake"
      "surname" => "L"
      "registration_id" => 24
      "registration_type_id" => "1"
      "updated_at" => "2018-06-03 13:07:18"
      "created_at" => "2018-06-03 13:07:18"
      "id" => 48
    ]
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #guarded: array:1 [
      0 => "*"
    ]
  }
]

Ответы [ 2 ]

0 голосов
/ 04 июня 2018

Вы просматриваете множество вопросов, которые могут или не могут быть связаны с массивом участников.Массив вопросов приходит из $ запроса, возвращаемого из POST:

<input type="checkbox" name="participant_question[]" value="No" class="form-check-input" 1="">    
    <input type="hidden" name="participant_question_required[]" value="1">
    <input type="hidden" value="2" name="participant_question_id[]">

и т. Д.

НО, вы делаете массив участников (и создаете их идентификаторы) независимым от количества вопросов.То есть у вас может быть 11 вопросов, которые делают этот цикл здесь:

 @foreach($selectedRtype['questions'] as $customQuestion)

И, таким образом, когда вы делаете цикл на стороне создания:

 for($i=0; $i < count($request->participant_question); $i++)

$ я мог бы === 10. Однако, вы можете иметь только 2 новых участника из формы.Это будет означать, что ваш $participants[] будет состоять только из $participants[0] и $participants[1].Таким образом, при циклическом цикле внутри массива вопросов (который имеет счетчик 11), ваш массив участников будет терпеть неудачу, когда он получит индекс 1 (он потерпит неудачу, когда $i === 2 делает вызов $participants[2]), так как всего их всего 2в массиве.

Чтобы исправить это, вы должны удалить

'participant_id' => $participants[$i]->id,

из массива создания.Опять же, количество участников не связано с количеством вопросов, поэтому это не удастся.Вам необходимо напрямую связать нового участника с вопросом.Возможно, когда вы создаете участника, ТО проверяйте, на какой вопрос он ответил, просматривая цикл имя-участника.Вы не можете сделать это со своим существующим кодом - вы пытаетесь связать две вещи, которые не связаны в форме.Я думаю, что вам нужно изменить либо связь в форме, либо найти способ объединить нового участника с вопросом, на который он конкретно ответил.Но это выходит за рамки этого вопроса - причина, по которой он не работает, состоит в том, что у вас есть два разных массива с двумя разными значениями.

0 голосов
/ 03 июня 2018

Из ошибки довольно очевидно, что массив "members" не имеет значений, кроме указателя $ i, заданного в вашем операторе цикла FOR.Я также заметил, что вы не правильно закрыли свои операторы IF и FOR.Вы также можете проверить это.

if(isset($request->participant_question))
    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],
        ]);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...