SegFaultDev
SegFaultDev

Reputation: 583

How to create a form that contains data for multiple entities?

I've been trying to think of the best possible way to submit data for multiple entities in a single form.

My use case is that I have a table that contains multiple rows of different entities. I want the ability to go into 'edit' view where some of the columns will become textfields and allow for the value to be changed.

Example

Type   | Name  | Age
Animal | Eevee | 4
Animal | Sandy | 7
Human  | Bob   | 24

[Submit]

In edit mode they would be able to change the age for any of the entities. When the user hits save button for the entire list, I want the form to submit all the changes. The problem is that in the update method, I need to know which entities to update with which values


I was thinking of using name attribute to store the entity id of each entity on the input

<input name="{{$entity->id}} value="{{$entity->age}}"></input>

but Animals and Humans are stored in different DB tables. So in the update method of the controller I would have to take the name (which would be the id of the entity) and if it exists as a human

entityToUpdate = Human::find(id)

if entityToUpdate does not exist

entityToUpdate = Animal::find(id)

We use UUIDs in our DB so this would work but it doesn't feel right.


is there a way to group a couple inputs together in a form?

group1
    type=animal
    id = (Sandys ID)
    age = 8
group2
    type=human
    id =(bobs ID)
    age = 25

Upvotes: 0

Views: 168

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50777

You could use array notation in your input names in order to get what you want on the server side:

@foreach($entities as $entity)
   <input type="hidden" name="group[{{$loop->index}}][type]" value="{{$entity->type}}"/>
   <input type="hidden" name="group[{{$loop->index}}][id] value="{{$entity->id}}"/>
   <input type="text" name="group[{{$loop->index}}][age] value="{{$entity->age}}"/>
@endforeach

Then on the server side:

foreach(request()->get('group') as $entity) {
    // $entity contains ['id'], ['type'], ['age']
}

Upvotes: 2

Related Questions