Two Dimensional HTML form data with Laravel

October 31, 2020

How to pass two dimensional data of a HTML form to Laravel Control

<table>

   <tr>
     <th><label class="label is-field-title">Day</label></th>
     <th><label class="label is-field-title">Start</label></th>
     <th><label class="label is-field-title">End</label></th>
    </tr>

  @foreach ($hours as $hour)
    <tr>
     <input type="hidden" name="hours[{{$hour->id}}][id]" value="{{$hour->id}}" />
     <td><input value="{{$hour->day}}" class="input is-small" type="text" name="hours[{{$hour->id}}][day]" /> </td>
     <td><input value="{{$hour->start}} "class="input is-small" type="text" name="hours[{{$hour->id}}][start]" /> </td>
     <td><input value="{{$hour->end}}" class="input is-small" type="text" name="hours[{{$hour->id}}][end]" /> </td>
    </tr>

  @endforeach
</table>
Two dimensional HTML Form

Most important thing here is the naming of the controls

name="hours[{{$hour->id}}][id]"

Inside the Laravel control you can read the post data as below

$hours = $request->input('hours');
         
foreach($hours as $hourid =>$hour){
     $obj = new Hours();
     $obj->day= $hour['day'];
     $obj->start= $hour['start'];
     $obj->end= $hour['end'];
     $obj->business_id = $business->id;
     $obj->save();
}