0

I have the following database:

id | name | age |
-----------------
 1 | John |  20 |
 2 | Jack |  29 |

I want to edit them all in a single form with the ability to "Add more" and then save/update as needed. How is that achievable with Laravel?

My form currently is this:

@foreach($people as $person)
    <input type="text" name="name[]" class="form-control" value="{{ $person->name }}">
    <input type="text" name="age[]" class="form-control" value="{{ $person->age }}">
@endforeach

Then in Laravel I receive the $request->all() as follows:

  "name" => array:2 [▼
    0 => "John"
    1 => "Jack"
  ]
  "name" => array:2 [▼
    0 => "20"
    1 => "29"
  ]

Which I guess is expected, but not convenient to work with Eloquent. What would be the Eloquent/Laravel way of doing this?

Note: In the real world example I'm developing Name is unique.

Using Laravel 7.

1 Answer 1

1

You should use the user id to identify every row of results

@foreach($people as $person)
    <input type="text" name="users[$person->id][name]" class="form-control" value="{{ $person->name }}">
    <input type="text" name="users[$person->id][age]" class="form-control" value="{{ $person->age }}">
@endforeach

You would get the request as follows:

[
    "users" => [
        1 => [
            'name' => 'John',
            'age' => 20
        ],
        2 => [
            'name' => 'Jack',
            'age' => 29
        ]
    ]
]
Sign up to request clarification or add additional context in comments.

2 Comments

Just to add on to what Lloople said, add rules too for unique names in the controller.
Why should be the name unique? There are three people called John at my office.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.