Laravel 7, how to call iterate an input that has no right name

Asked

Viewed 68 times

-1

I am making a small form in Laravel 7 and in Javascript I have a button that adds the fields that the user needs to create the necessary questions.

Javascript

$(btnQuestions).click(function () {
            $('<div class="form-group" id="div_questions"><label for="data_type">Tipo de pergunta</label><input type="text" name="data_type'+i+'" id="data_type'+i+'" class="form-control"><label for="question'+i+'">Pergunta</label><input type="text" name="question'+i+'" id="question'+i+'" class="form-control"></div>').appendTo(divQuestions);
            $('#removehidden').remove();
            i++;
            $('<input type="hidden" name="quantidadeCampos" value="' + i + '" id="removehidden">').appendTo(divQuestions);
        });

My question now is how in Controller I can call what is inserted in inputs and "name" changes whenever we add a new field

Controller

public function store(Request $request)
    {
        $request->validate([
            'name_form' =>'required',
            'description' => 'required',
            'email' => 'required',
            'end_date' => 'required', 
            'data_type' => 'required',
            'question' => 'required'
        ]);

        $form = new Form([
            'name_form' => $request->get('name_form'),
            'description'=> $request->get('description'),
            'email'=> $request->get('email'),
            'end_date' => $request->get('end_date')           
        ]);

        $form->save();

        /*$data_type = $request->get('data_type');
        $quest = $request->get('question');*/
        $questions = array('data_type', 'question');

        for ($i = 1; $i <= count($questions); $i++) {
            $question = new Question([
               'data_type' => $request->get('data_type'),
               'question' => $request->get('question'),
               'form_id' => $form->id
            ]);
            $question->save();
        }

        return redirect('/backoffice/forms')->with('success', 'O formulário foi criado com sucesso.');
    }

If anyone can help me, thank you

1 answer

0

Hi, how are you? Instead of using 'data_type' + id in the input name, we can use an array.

<input name="data_type[]">

This way, the request->data_type will arrive in the controller as a array, as follows:

data_type = ['Field1', 'Field2'];

This way, when we iterate over the data_type, we will have all information concentrated in a single name array data_type only

foreach ($request->data_type as $data_type) {
   dd($data_type); // Return 'Field 1'
}

Thus, its creation of questions would be as follows:

foreach ($request->data_type as $data_type) {
   'data_type' => $data_type,
   'question' => $request->get('question'),
   'form_id' => $form->id
}

For more details about the array in name

Browser other questions tagged

You are not signed in. Login or sign up in order to post.