J
J
Johnny Show2020-05-06 21:15:58
HTML
Johnny Show, 2020-05-06 21:15:58

How to get and write to the database all the data from the dynamic form field?

There is a standard form, the Phone field is dynamic, you can add several fields with the same name.
It is not possible to Send all the data of this field to the database and then receive it.
Only the last record of this field is sent to the database.
view:

<form method="POST" action="{{route('posts.store')}}">
            {{ csrf_field() }}
            <button type="submit" class="btn btn-success mb-3">Добавить запись</button>

            <div class="form-group">
                <label for="post-name">Имя</label>
                <input type="text" name="name" value="{{old('name')}}" class="form-control" id="post-name">
            </div>
            <div class="form-group">
                <label for="post-surname">Фамилия</label>
                <input class="form-control" type="text" name="surname" value="{{old('surname')}}" id="post-surname">


            </div>
            <label for="post-phone">Телефон</label>
            <div class="entry input-group" id="dynamic_field">
                <input type="phone" name="phone" value="{{old('phone')}}" class="form-control" id="post-phone">
                <span class="input-group-btn">
                            <button class="btn btn-success btn-add" name="add" id="add" type="button">
                                <span class="glyphicon glyphicon-plus"></span>
                            </button>
                        </span>

            </div>

        </form>

controller:
public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
            'surname' => 'required|max:255',
            'phone' => 'required',
        ]);

        $post = new Post([
           'name' => $request->get('name'),
           'surname' => $request->get('surname'),
           'phone' => $request->get('phone'),
        ]);
        $post->save();
        return redirect('/posts')->with('success', 'Запись добавлена');
    }

Sending:
5eb2fe803afc6039824669.jpeg
Receiving:
5eb2fe89ee1ff175535471.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2020-05-06
@X-core

You have multiple fields with the same name 'phone'. Accordingly, when parsing the query string, PHP stores only the last one in $_POST['phone'] .
You can pass fields as an array by specifying name='phone[]'.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question